import { describe, it, expect } from 'vitest';
import { EventEmitter } from 'events';
import { createPrompter } from './prompts.js';
import { ConfigBuilder } from './config.js';
import { setupChannels } from './channels.js';

function mockReadline(inputs: string[]) {
  let questionIdx = 0;
  const emitter = new EventEmitter();

  return {
    async question(query: string) {
      const answer = inputs[questionIdx++];
      return answer ?? '';
    },

    close() {
      // no-op
    },

    [Symbol.asyncIterator]() {
      return this;
    },

    async next() {
      return { done: true };
    },
  } as any;
}

describe('setupChannels', () => {
  it('configures webchat only (default)', async () => {
    const rl = mockReadline(['', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupChannels(p, builder);
    const config = builder.build();
    expect(config.server.port).toBeDefined();
    expect(config.telegram).toBeUndefined();
  });

  it('configures telegram channel', async () => {
    const rl = mockReadline(['', 'y', '1', '123:ABC', '12345, 67890', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupChannels(p, builder);
    const config = builder.build();
    expect(config.telegram.bot_token).toBe('123:ABC');
    expect(config.telegram.allowed_chat_ids).toEqual([12345, 67890]);
  });

  it('configures discord channel', async () => {
    const rl = mockReadline(['', 'y', '2', 'MTIz.token', 'guild1, guild2', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupChannels(p, builder);
    const config = builder.build();
    expect(config.discord.bot_token).toBe('MTIz.token');
    expect(config.discord.allowed_guild_ids).toEqual(['guild1', 'guild2']);
  });
});
