import TelegramBot from 'node-telegram-bot-api';
import { getServerIntegration } from 'officerdb';
import { handleTelegramMessage } from './handler';

let bot: TelegramBot | null = null;
let cachedUsername: string | null = null;

export async function startTelegramBot(token: string): Promise<void> {
  if (bot) {
    await stopTelegramBot();
  }

  bot = new TelegramBot(token, { polling: true });

  bot.on('message', (msg) => {
    handleTelegramMessage(msg).catch((err) => {
      console.error('[telegram] Unhandled error in message handler:', err);
    });
  });

  const me = await bot.getMe();
  cachedUsername = me.username ?? null;
  console.log(`[telegram] Bot logged in as @${cachedUsername}`);
}

export async function stopTelegramBot(): Promise<void> {
  if (bot) {
    await bot.stopPolling();
    bot = null;
    cachedUsername = null;
    console.log('[telegram] Bot stopped');
  }
}

export function isTelegramBotRunning(): boolean {
  return bot !== null && bot.isPolling();
}

export function getTelegramBotUsername(): string | null {
  return cachedUsername;
}

export function getTelegramBot(): TelegramBot | null {
  return bot;
}

export async function startTelegramBotIfConfigured(): Promise<void> {
  const integration = await getServerIntegration('telegram');
  if (!integration?.enabled) return;

  const config = integration.config as Record<string, unknown>;
  const botToken = config.botToken as string | undefined;
  if (!botToken) return;

  await startTelegramBot(botToken);
}
