import { describe, it, expect, beforeEach } from '@jest/globals';
import { Shield } from '@4runr/shield';
import {
  applyShieldConfigFromEnv,
  buildShieldConfigFromEnv,
  validateShieldProductionConfig,
} from '../security/shield-config.js';

function resetShieldSingleton(): void {
  (Shield as unknown as { instance?: Shield }).instance = undefined;
}

describe('shield-config', () => {
  beforeEach(() => {
    resetShieldSingleton();
  });

  it('buildShieldConfigFromEnv maps off to disabled', () => {
    expect(buildShieldConfigFromEnv('off')).toEqual({
      enabled: false,
      mode: 'off',
    });
  });

  it('buildShieldConfigFromEnv keeps enforce enabled', () => {
    expect(buildShieldConfigFromEnv('enforce')).toEqual({
      enabled: true,
      mode: 'enforce',
    });
  });

  it('applyShieldConfigFromEnv updates singleton mode', () => {
    const shield = Shield.getInstance();
    applyShieldConfigFromEnv(shield, 'monitor');
    expect(shield.getConfig().mode).toBe('monitor');
    expect(shield.isEnabled()).toBe(true);

    applyShieldConfigFromEnv(shield, 'off');
    expect(shield.getConfig().mode).toBe('off');
    expect(shield.isEnabled()).toBe(false);
  });

  it('validateShieldProductionConfig warns when rewrite lacks API key', () => {
    const shield = Shield.getInstance();
    const config = applyShieldConfigFromEnv(shield, 'enforce');
    const { warnings } = validateShieldProductionConfig(config, {
      nodeEnv: 'production',
      openAiApiKey: undefined,
    });
    expect(warnings.some((w) => w.includes('OPENAI_API_KEY'))).toBe(true);
  });

  it('validateShieldProductionConfig warns when Shield off in production', () => {
    const shield = Shield.getInstance();
    const config = applyShieldConfigFromEnv(shield, 'off');
    const { warnings } = validateShieldProductionConfig(config, {
      nodeEnv: 'production',
    });
    expect(warnings.some((w) => w.includes('disabled'))).toBe(true);
  });
});
