import { describe, it, expect } from 'vitest';
import { McpctlConfigSchema, DEFAULT_CONFIG } from '../../src/config/schema.js';

describe('McpctlConfigSchema', () => {
  it('provides sensible defaults from empty object', () => {
    const config = McpctlConfigSchema.parse({});
    expect(config.mcplocalUrl).toBe('http://localhost:3200');
    expect(config.mcpdUrl).toBe('http://localhost:3100');
    expect(config.registries).toEqual(['official', 'glama', 'smithery']);
    expect(config.cacheTTLMs).toBe(3_600_000);
    expect(config.outputFormat).toBe('table');
    expect(config.httpProxy).toBeUndefined();
    expect(config.httpsProxy).toBeUndefined();
    expect(config.smitheryApiKey).toBeUndefined();
  });

  it('validates a full config', () => {
    const config = McpctlConfigSchema.parse({
      mcplocalUrl: 'http://local:3200',
      mcpdUrl: 'http://custom:4000',
      registries: ['official'],
      cacheTTLMs: 60_000,
      httpProxy: 'http://proxy:8080',
      httpsProxy: 'http://proxy:8443',
      outputFormat: 'json',
      smitheryApiKey: 'sk-test',
    });
    expect(config.mcplocalUrl).toBe('http://local:3200');
    expect(config.mcpdUrl).toBe('http://custom:4000');
    expect(config.registries).toEqual(['official']);
    expect(config.outputFormat).toBe('json');
  });

  it('backward compat: maps daemonUrl to mcplocalUrl', () => {
    const config = McpctlConfigSchema.parse({ daemonUrl: 'http://legacy:3000' });
    expect(config.mcplocalUrl).toBe('http://legacy:3000');
    expect(config.mcpdUrl).toBe('http://localhost:3100');
  });

  it('mcplocalUrl takes precedence over daemonUrl', () => {
    const config = McpctlConfigSchema.parse({
      daemonUrl: 'http://legacy:3000',
      mcplocalUrl: 'http://explicit:3200',
    });
    expect(config.mcplocalUrl).toBe('http://explicit:3200');
  });

  it('rejects invalid registry names', () => {
    expect(() => McpctlConfigSchema.parse({ registries: ['invalid'] })).toThrow();
  });

  it('rejects invalid output format', () => {
    expect(() => McpctlConfigSchema.parse({ outputFormat: 'xml' })).toThrow();
  });

  it('rejects negative cacheTTLMs', () => {
    expect(() => McpctlConfigSchema.parse({ cacheTTLMs: -1 })).toThrow();
  });

  it('rejects non-integer cacheTTLMs', () => {
    expect(() => McpctlConfigSchema.parse({ cacheTTLMs: 1.5 })).toThrow();
  });
});

describe('DEFAULT_CONFIG', () => {
  it('matches schema defaults', () => {
    expect(DEFAULT_CONFIG).toEqual(McpctlConfigSchema.parse({}));
  });
});
