import type { Prompter } from './prompts.js';
import type { ConfigBuilder } from './config.js';

async function setupTelegram(p: Prompter, builder: ConfigBuilder): Promise<void> {
  p.println('  1. Message @BotFather on Telegram and use /newbot to create a bot');
  p.println('  2. Copy the bot token it gives you');
  p.println('  3. To find your chat ID, message @userinfobot or @RawDataBot');
  const botToken = await p.password('Bot token (from @BotFather)');
  const chatIdsRaw = await p.ask('Allowed chat IDs (comma-separated)');
  const chatIds = chatIdsRaw.split(',').map(s => parseInt(s.trim(), 10)).filter(n => !isNaN(n));
  if (chatIds.length === 0) {
    p.println('No valid chat IDs entered. Skipping Telegram.');
    return;
  }
  builder.setTelegram(botToken, chatIds);
  p.println('✓ Telegram configured');
}

async function setupDiscord(p: Prompter, builder: ConfigBuilder): Promise<void> {
  p.println('  1. Go to https://discord.com/developers/applications');
  p.println('  2. Create an application → Bot → copy the bot token');
  p.println('  3. Enable MESSAGE CONTENT intent under Bot settings');
  p.println('  4. Invite bot to your server with OAuth2 URL Generator (bot scope + Send Messages)');
  p.println('  5. Guild ID: right-click your server → Copy Server ID (enable Developer Mode in settings)');
  const botToken = await p.password('Bot token');
  const guildIdsRaw = await p.ask('Allowed guild IDs (comma-separated, or * for all)');
  const guildIds = guildIdsRaw === '*' ? [] : guildIdsRaw.split(',').map(s => s.trim()).filter(Boolean);
  builder.setDiscord(botToken, guildIds);
  p.println('✓ Discord configured');
}

async function setupSlack(p: Prompter, builder: ConfigBuilder): Promise<void> {
  p.println('  1. Go to https://api.slack.com/apps and create a new app');
  p.println('  2. Enable Socket Mode → generate an App Token (xapp-...)');
  p.println('  3. Under OAuth & Permissions, install to workspace → copy Bot Token (xoxb-...)');
  p.println('  4. Under Basic Information → copy Signing Secret');
  p.println('  5. Channel IDs: right-click a channel → View channel details → copy the ID at bottom');
  const botToken = await p.password('Bot token (xoxb-...)');
  const appToken = await p.password('App token (xapp-...)');
  const signingSecret = await p.password('Signing secret');
  const channelIdsRaw = await p.ask('Allowed channel IDs (comma-separated, or * for all)');
  const channelIds = channelIdsRaw === '*' ? [] : channelIdsRaw.split(',').map(s => s.trim()).filter(Boolean);
  builder.setSlack(botToken, appToken, signingSecret, channelIds);
  p.println('✓ Slack configured');
}

async function setupWhatsApp(p: Prompter, builder: ConfigBuilder): Promise<void> {
  p.println('⚠ WhatsApp requires QR code authentication on first connect.');
  p.println('  It will appear in the terminal when Flynn starts.');
  const numbersRaw = await p.ask('Allowed phone numbers (comma-separated, or * for all)');
  const numbers = numbersRaw === '*' ? [] : numbersRaw.split(',').map(s => s.trim()).filter(Boolean);
  builder.setWhatsApp(numbers);
  p.println('✓ WhatsApp configured');
}

const CHANNEL_OPTIONS = [
  { label: 'Telegram', value: 'telegram' as const },
  { label: 'Discord', value: 'discord' as const },
  { label: 'More channels...', value: 'more' as const },
];

const MORE_CHANNEL_OPTIONS = [
  { label: 'Slack', value: 'slack' as const },
  { label: 'WhatsApp', value: 'whatsapp' as const },
];

const CHANNEL_SETUP: Record<string, (p: Prompter, b: ConfigBuilder) => Promise<void>> = {
  telegram: setupTelegram,
  discord: setupDiscord,
  slack: setupSlack,
  whatsapp: setupWhatsApp,
};

export async function setupChannels(p: Prompter, builder: ConfigBuilder): Promise<void> {
  p.println();
  p.println('WebChat is enabled by default via the gateway.');
  const port = await p.ask('Gateway port', '18800');
  builder.setGatewayPort(parseInt(port, 10) || 18800);
  p.println('✓ WebChat enabled — visit http://localhost:' + port + ' after starting');

  let addMore = await p.confirm('Add a messaging channel?', false);

  while (addMore) {
    p.println();
    const choice = await p.choose('Channel:', CHANNEL_OPTIONS);

    if (choice === 'more') {
      const moreChoice = await p.choose('Channel:', MORE_CHANNEL_OPTIONS);
      const setup = CHANNEL_SETUP[moreChoice];
      if (setup) {await setup(p, builder);}
    } else {
      const setup = CHANNEL_SETUP[choice];
      if (setup) {await setup(p, builder);}
    }

    p.println();
    addMore = await p.confirm('Add another channel?', false);
  }
}
