import { Bot } from 'grammy';
import { config } from '../config';
import { getRedis, REDIS_KEYS } from '../redis';
import { appendAgentMessage, getSessionWithMessages } from '../support/service';
import { formatSupportHistory } from '../support/telegram';

let _supportBot: Bot | null = null;

export function getSupportBot(): Bot | null {
  return _supportBot;
}

function isSupportAdmin(chatId: number): boolean {
  return config.supportTg.chatIds.includes(String(chatId));
}

export function startSupportBot(): void {
  if (!config.supportTg.token) {
    console.log('[support-bot] SUPPORT_TG_BOT_TOKEN not set, support bot disabled');
    return;
  }
  if (config.supportTg.chatIds.length === 0) {
    console.log('[support-bot] SUPPORT_TG_CHAT_ID not set, support bot disabled');
    return;
  }

  _supportBot = new Bot(config.supportTg.token);
  const bot = _supportBot;

  bot.use(async (ctx, next) => {
    const chatId = ctx.chat?.id;
    if (!chatId || !isSupportAdmin(chatId)) {
      await ctx.reply('⛔ Нет доступа.');
      return;
    }
    await next();
  });

  bot.command('start', async (ctx) => {
    await ctx.reply(
      '💬 <b>Sinsay Support Bot</b>\n\n' +
        'Ответьте <b>Reply</b> на уведомление о сообщении клиента, чтобы отправить ответ в чат на сайте.\n' +
        'Кнопка «📜 Посмотреть историю чата» показывает переписку.',
      { parse_mode: 'HTML' },
    );
  });

  bot.callbackQuery(/^support:history:(.+)$/, async (ctx) => {
    const sessionId = ctx.match[1];
    await ctx.answerCallbackQuery();
    try {
      const session = await getSessionWithMessages(sessionId);
      if (!session) {
        await ctx.reply('Сессия чата не найдена.');
        return;
      }
      await ctx.reply(formatSupportHistory(session, session.messages), { parse_mode: 'HTML' });
    } catch (err) {
      await ctx.reply('❌ Ошибка: ' + (err as Error).message);
    }
  });

  bot.on('message:text', async (ctx) => {
    const replyTo = ctx.message.reply_to_message;
    const text = ctx.message.text?.trim() ?? '';
    if (!replyTo || !text || text.startsWith('/')) {
      return;
    }

    const redis = getRedis();
    const sessionId = await redis.get(REDIS_KEYS.supportTgMessage(replyTo.message_id));
    if (!sessionId) {
      return;
    }

    try {
      await appendAgentMessage(sessionId, text);
      await ctx.reply('✅ Ответ отправлен клиенту в чат.');
    } catch (err) {
      await ctx.reply('❌ Не удалось отправить ответ: ' + (err as Error).message);
    }
  });

  bot.start({ onStart: () => console.log('[support-bot] Telegram support bot polling started') });
}
