// tests/policy.test.js

require('../__mocks__/chrome.js');
const { loadPolicy, savePolicy, checkPolicy } = require('../lib/policy.js');

describe('Policy', () => {
  beforeEach(() => {
    global.__chromeStore = {};
  });

  test('loadPolicy returns default policy when none stored', async () => {
    const policy = await loadPolicy();
    expect(policy).toBeDefined();
    expect(policy.version).toBe(1);
    expect(policy.rules).toHaveLength(6);
    expect(policy.rules[0].type).toBe('allowed_domains');
  });

  test('savePolicy increments version', async () => {
    const policy = await loadPolicy();
    const saved = await savePolicy(policy);
    expect(saved.version).toBe(2);
  });

  test('checkPolicy allows permitted domains', () => {
    const event = {
      type: 'api_call',
      tool: 'fetch',
      target: 'https://github.com/api',
      url: 'https://claude.ai/chat'
    };
    const policy = {
      rules: [
        { id: 'rule1', type: 'allowed_domains', enabled: true, params: { domains: ['github.com'] } }
      ]
    };
    const result = checkPolicy(event, policy);
    expect(result.outcome).toBe('allowed');
    expect(result.severity).toBe('info');
  });

  test('checkPolicy flags disallowed domains', () => {
    const event = {
      type: 'api_call',
      tool: 'fetch',
      target: 'https://evil.com/api',
      url: 'https://claude.ai/chat'
    };
    const policy = {
      rules: [
        { id: 'rule1', type: 'allowed_domains', enabled: true, params: { domains: ['github.com'] } }
      ]
    };
    const result = checkPolicy(event, policy);
    expect(result.outcome).toBe('violation');
    expect(result.severity).toBe('high');
    expect(result.ruleId).toBe('rule1');
  });

  test('checkPolicy flags disallowed tools', () => {
    const event = {
      type: 'tool_use',
      tool: 'eval',
      target: 'script.js',
      url: 'https://claude.ai/chat'
    };
    const policy = {
      rules: [
        { id: 'rule1', type: 'disallowed_tools', enabled: true, params: { tools: ['eval'] } }
      ]
    };
    const result = checkPolicy(event, policy);
    expect(result.outcome).toBe('violation');
    expect(result.severity).toBe('critical');
  });

  test('disabled rules are ignored', () => {
    const event = {
      type: 'tool_use',
      tool: 'eval',
      target: 'script.js',
      url: 'https://claude.ai/chat'
    };
    const policy = {
      rules: [
        { id: 'rule1', type: 'disallowed_tools', enabled: false, params: { tools: ['eval'] } }
      ]
    };
    const result = checkPolicy(event, policy);
    expect(result.outcome).toBe('allowed');
  });
});
