import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import type { ChannelManager } from '../modules/telegram-manager/channel-manager.js';
import type { TelegramManager } from '../modules/telegram-manager/index.js';

interface TelegramRouteOpts extends FastifyPluginOptions {
  channelManager: ChannelManager;
  telegramManager: TelegramManager;
}

export default async function telegramRoutes(app: FastifyInstance, opts: TelegramRouteOpts) {
  const { channelManager, telegramManager } = opts;

  // POST /characters/:id/channels — Create channels (Normal + VIP)
  app.post('/characters/:id/channels', async (request, reply) => {
    const { id } = request.params as { id: string };
    const body = request.body as {
      normalTitle?: string;
      vipTitle?: string;
    } | null;

    try {
      const botClient = telegramManager.getBotClient(id);
      if (!botClient) {
        return reply.status(400).send({ success: false, error: 'No bot configured for this character' });
      }

      const normalTitle = body?.normalTitle || `Character ${id} Channel`;
      const vipTitle = body?.vipTitle || `Character ${id} VIP`;

      const config = await channelManager.createChannels(id, botClient as any, normalTitle, vipTitle);
      return reply.status(201).send({ success: true, data: config });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  // GET /characters/:id/channels — Get channel info
  app.get('/characters/:id/channels', async (request, reply) => {
    const { id } = request.params as { id: string };

    try {
      const config = await channelManager.getChannelConfig(id);
      if (!config) {
        return reply.status(404).send({ success: false, error: 'No channels configured for this character' });
      }
      return reply.status(200).send({ success: true, data: config });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });


  // PUT /characters/:id/channels/:channelType — Update channel settings
  app.put('/characters/:id/channels/:channelType', async (request, reply) => {
    const { id, channelType } = request.params as { id: string; channelType: string };
    const body = request.body as Record<string, unknown> | null;

    if (channelType !== 'normal' && channelType !== 'vip') {
      return reply.status(400).send({ success: false, error: 'channelType must be "normal" or "vip"' });
    }

    if (!body) {
      return reply.status(400).send({ success: false, error: 'Request body is required' });
    }

    try {
      const updates: Record<string, unknown> = {};
      if (channelType === 'normal') {
        updates.normalChannel = body;
      } else {
        updates.vipChannel = body;
      }
      if (body.publishSchedule !== undefined) {
        updates.publishSchedule = body.publishSchedule;
      }

      const config = await channelManager.updateChannelConfig(id, updates as any);
      return reply.status(200).send({ success: true, data: config });
    } catch (err: any) {
      if (err.message?.includes('not found')) {
        return reply.status(404).send({ success: false, error: err.message });
      }
      return reply.status(400).send({ success: false, error: err.message });
    }
  });

  // POST /characters/:id/channels/:channelType/publish — Publish content
  app.post('/characters/:id/channels/:channelType/publish', async (request, reply) => {
    const { id, channelType } = request.params as { id: string; channelType: string };
    const body = request.body as {
      text?: string;
      photoUrl?: string;
      caption?: string;
      imageUrl?: string;
      starCount?: number;
    } | null;

    if (channelType !== 'normal' && channelType !== 'vip') {
      return reply.status(400).send({ success: false, error: 'channelType must be "normal" or "vip"' });
    }

    if (!body) {
      return reply.status(400).send({ success: false, error: 'Request body is required' });
    }

    try {
      if (channelType === 'normal') {
        await channelManager.publishToNormal(id, {
          text: body.text,
          photoUrl: body.photoUrl,
          caption: body.caption,
        });
      } else {
        if (!body.imageUrl) {
          return reply.status(400).send({ success: false, error: 'imageUrl is required for VIP channel publish' });
        }
        await channelManager.publishToVIP(id, body.imageUrl, body.starCount || 50, body.caption);
      }
      return reply.status(200).send({ success: true, data: { published: true } });
    } catch (err: any) {
      if (err.message?.includes('not configured') || err.message?.includes('not available')) {
        return reply.status(400).send({ success: false, error: err.message });
      }
      return reply.status(500).send({ success: false, error: err.message });
    }
  });
}
