import { describe, it, expect } from 'vitest';
import { createPrompter } from './prompts.js';
import { ConfigBuilder } from './config.js';
import { setupMemory } from './memory.js';
import { setupSecurity } from './security.js';
import { setupGateway } from './gateway.js';

function mockReadline(inputs: string[]) {
  let questionIdx = 0;

  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('setupMemory', () => {
  it('enables vector search with openai embeddings', async () => {
    const rl = mockReadline(['y', '1', 'y']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    builder.setProvider('default', { provider: 'openai', model: 'gpt-4.1', api_key: 'sk-test' });
    await setupMemory(p, builder);
    const config = builder.build();
    expect(config.memory.embedding.enabled).toBe(true);
    expect(config.memory.embedding.provider).toBe('openai');
  });

  it('skips vector search when declined', async () => {
    const rl = mockReadline(['n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupMemory(p, builder);
    const config = builder.build();
    expect(config.memory?.embedding?.enabled).toBeFalsy();
  });
});

describe('setupSecurity', () => {
  it('enables sandbox and pairing', async () => {
    const rl = mockReadline(['y', 'y', '']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupSecurity(p, builder);
    const config = builder.build();
    expect(config.sandbox.enabled).toBe(true);
    expect(config.pairing.enabled).toBe(true);
  });
});

describe('setupGateway', () => {
  it('configures port and auth token', async () => {
    const rl = mockReadline(['9999', 'y', 'my-token', 'n', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupGateway(p, builder);
    const config = builder.build();
    expect(config.server.port).toBe(9999);
    expect(config.server.token).toBe('my-token');
  });
});
