import { describe, it, expect } from 'vitest';
import { baseBackendConfigSchema, parseBackendConfig } from './index.js';

describe('baseBackendConfigSchema', () => {
  it('parses minimal valid env', () => {
    const config = baseBackendConfigSchema.parse({
      JWT_SECRET: 'test-secret',
    });
    expect(config.PORT).toBe(3000);
    expect(config.HOST).toBe('0.0.0.0');
    expect(config.NODE_ENV).toBe('development');
    expect(config.DB_PROVIDER).toBe('cosmos');
    expect(config.COSMOS_DATABASE).toBe('lysnrai');
    expect(config.JWT_SECRET).toBe('test-secret');
    expect(config.PLATFORM_JWKS_URL).toBeUndefined();
  });

  it('applies overrides', () => {
    const config = baseBackendConfigSchema.parse({
      PORT: '4010',
      NODE_ENV: 'production',
      DB_PROVIDER: 'memory',
      JWT_SECRET: 'prod-secret',
      PLATFORM_JWKS_URL: 'https://example.com/.well-known/jwks.json',
    });
    expect(config.PORT).toBe(4010);
    expect(config.NODE_ENV).toBe('production');
    expect(config.DB_PROVIDER).toBe('memory');
    expect(config.PLATFORM_JWKS_URL).toBe('https://example.com/.well-known/jwks.json');
  });

  it('rejects missing JWT_SECRET', () => {
    expect(() => baseBackendConfigSchema.parse({})).toThrow();
  });

  it('rejects invalid NODE_ENV', () => {
    expect(() => baseBackendConfigSchema.parse({ JWT_SECRET: 's', NODE_ENV: 'staging' })).toThrow();
  });

  it('rejects invalid DB_PROVIDER', () => {
    expect(() =>
      baseBackendConfigSchema.parse({ JWT_SECRET: 's', DB_PROVIDER: 'postgres' })
    ).toThrow();
  });
});

describe('baseBackendConfigSchema.extend()', () => {
  const extendedSchema = baseBackendConfigSchema.extend({
    PLATFORM_SERVICE_URL: baseBackendConfigSchema.shape.HOST.default('http://localhost:4003'),
    CUSTOM_FLAG: baseBackendConfigSchema.shape.NODE_ENV.optional(),
  });

  it('parses extended config with product-specific fields', () => {
    const config = extendedSchema.parse({
      JWT_SECRET: 'test-secret',
      PORT: '4018',
      SERVICE_NAME: 'actiontrail-backend',
    });
    expect(config.PORT).toBe(4018);
    expect(config.SERVICE_NAME).toBe('actiontrail-backend');
    expect(config.PLATFORM_SERVICE_URL).toBe('http://localhost:4003');
  });
});

describe('parseBackendConfig', () => {
  it('parses from explicit env object', () => {
    const config = parseBackendConfig(baseBackendConfigSchema, {
      JWT_SECRET: 'from-env',
      PORT: '9999',
    });
    expect(config.JWT_SECRET).toBe('from-env');
    expect(config.PORT).toBe(9999);
  });

  it('works with extended schemas', () => {
    const schema = baseBackendConfigSchema.extend({
      WEBHOOK_SECRET: baseBackendConfigSchema.shape.HOST.default('dev-webhook'),
    });
    const config = parseBackendConfig(schema, { JWT_SECRET: 'x' });
    expect(config.WEBHOOK_SECRET).toBe('dev-webhook');
  });
});
