import { afterEach, describe, expect, it, vi } from 'vitest';

const REQUIRED_ENV = {
  COSMOS_ENDPOINT: 'https://example.documents.azure.com:443/',
  COSMOS_KEY: 'test-cosmos-key',
  JWT_SECRET: 'test-jwt-secret',
};

afterEach(() => {
  vi.resetModules();
  vi.unstubAllEnvs();
});

describe('lib/config', () => {
  it('parses with defaults when required env vars are set', async () => {
    vi.stubEnv('COSMOS_ENDPOINT', REQUIRED_ENV.COSMOS_ENDPOINT);
    vi.stubEnv('COSMOS_KEY', REQUIRED_ENV.COSMOS_KEY);
    vi.stubEnv('JWT_SECRET', REQUIRED_ENV.JWT_SECRET);

    const { config } = await import('./config.js');

    expect(config.PORT).toBe(4003);
    expect(config.HOST).toBe('0.0.0.0');
    expect(['development', 'test']).toContain(config.NODE_ENV);
    expect(config.COSMOS_DATABASE).toBe('lysnrai');
    expect(config.USAGE_WARN_THRESHOLD).toBe(0.8);
  });

  it('respects explicit env overrides', async () => {
    vi.stubEnv('COSMOS_ENDPOINT', REQUIRED_ENV.COSMOS_ENDPOINT);
    vi.stubEnv('COSMOS_KEY', REQUIRED_ENV.COSMOS_KEY);
    vi.stubEnv('JWT_SECRET', REQUIRED_ENV.JWT_SECRET);
    vi.stubEnv('PORT', '4999');
    vi.stubEnv('NODE_ENV', 'test');
    vi.stubEnv('SERVICE_NAME', 'platform-service-test');
    vi.stubEnv('USAGE_WARN_THRESHOLD', '0.9');
    vi.stubEnv('RATE_LIMIT_STORE_MODE', 'memory');
    vi.stubEnv(
      'API_KEY_RATE_LIMIT_CONFIG_JSON',
      '{"jobs:read":{"maxRequests":10,"windowSeconds":60}}'
    );
    vi.stubEnv(
      'API_KEY_PRODUCT_RATE_LIMIT_CONFIG_JSON',
      '{"jobs:read":{"maxRequests":20,"windowSeconds":60}}'
    );

    const { config } = await import('./config.js');

    expect(config.PORT).toBe(4999);
    expect(config.NODE_ENV).toBe('test');
    expect(config.SERVICE_NAME).toBe('platform-service-test');
    expect(config.USAGE_WARN_THRESHOLD).toBe(0.9);
    expect(config.RATE_LIMIT_STORE_MODE).toBe('memory');
    expect(config.API_KEY_RATE_LIMIT_CONFIG_JSON).toContain('"jobs:read"');
    expect(config.API_KEY_PRODUCT_RATE_LIMIT_CONFIG_JSON).toContain('"jobs:read"');
  });

  it('throws when required env vars are missing', async () => {
    vi.stubEnv('COSMOS_ENDPOINT', '');
    vi.stubEnv('COSMOS_KEY', '');
    vi.stubEnv('JWT_SECRET', '');

    await expect(import('./config.js')).rejects.toThrow();
  });
});
