import { Client, GatewayIntentBits, Partials, Events } from 'discord.js';
import { getServerIntegration } from 'officerdb';
import { handleDiscordMessage } from './handler';

let client: Client | null = null;

export async function startDiscordBot(token: string): Promise<void> {
  if (client) {
    await stopDiscordBot();
  }

  client = new Client({
    intents: [
      GatewayIntentBits.Guilds,
      GatewayIntentBits.GuildMembers,
      GatewayIntentBits.GuildPresences,
      GatewayIntentBits.DirectMessages,
      GatewayIntentBits.MessageContent,
    ],
    partials: [Partials.Channel],
  });

  client.on(Events.MessageCreate, (message) => {
    handleDiscordMessage(message).catch((err) => {
      console.error('[discord] Unhandled error in message handler:', err);
    });
  });

  client.once(Events.ClientReady, (c) => {
    console.log(`[discord] Bot logged in as ${c.user.tag}`);
  });

  await client.login(token);
}

export async function stopDiscordBot(): Promise<void> {
  if (client) {
    client.destroy();
    client = null;
    console.log('[discord] Bot stopped');
  }
}

export function isDiscordBotRunning(): boolean {
  return client !== null && client.isReady();
}

export function getDiscordBotUsername(): string | null {
  return client?.user?.tag ?? null;
}

type DiscordConfig = {
  botToken: string;
};

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

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

  await startDiscordBot(botToken);
}
