import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';
import { validateSecrets } from '../middleware/security.js';

const ORIGINAL_ENV = { ...process.env };

describe('validateSecrets', () => {
  beforeEach(() => {
    process.env = { ...ORIGINAL_ENV };
    process.env['NODE_ENV'] = 'production';
    process.env['GATEWAY_PERSISTENCE'] = 'postgres';
    process.env['DATABASE_URL'] = 'postgresql://user:pass@localhost:5432/4runr';
    process.env['JWT_SECRET'] = 'a'.repeat(32);
    process.env['SIGNING_SECRET'] = 'b'.repeat(32);
    process.env['ENCRYPTION_KEY'] = 'c'.repeat(32);
    process.env['KEK_BASE64'] = Buffer.alloc(32).toString('base64');
    process.env['AUTH_MODE'] = 'api_key';
    process.env['AUTH_ENABLED'] = 'true';
  });

  afterEach(() => {
    process.env = { ...ORIGINAL_ENV };
  });

  it('passes with production postgres secrets', () => {
    const result = validateSecrets();
    expect(result.valid).toBe(true);
    expect(result.errors).toHaveLength(0);
  });

  it('fails when SIGNING_SECRET is missing in production', () => {
    delete process.env['SIGNING_SECRET'];
    const result = validateSecrets();
    expect(result.valid).toBe(false);
    expect(result.errors.some((e) => e.includes('SIGNING_SECRET'))).toBe(true);
  });

  it('fails when ENCRYPTION_KEY uses dev default in production', () => {
    process.env['ENCRYPTION_KEY'] = 'default-dev-key-change-in-production';
    const result = validateSecrets();
    expect(result.valid).toBe(false);
    expect(result.errors.some((e) => e.includes('ENCRYPTION_KEY'))).toBe(true);
  });

  it('skips ENCRYPTION_KEY and KEK when GATEWAY_PERSISTENCE=memory', () => {
    process.env['GATEWAY_PERSISTENCE'] = 'memory';
    delete process.env['ENCRYPTION_KEY'];
    delete process.env['KEK_BASE64'];
    const result = validateSecrets();
    expect(result.valid).toBe(true);
    expect(result.warnings.some((w) => w.includes('memory'))).toBe(true);
  });
});
