import { describe, it, expect, beforeEach } from 'vitest';
import { urlCache } from '../src/lib/cache';
import { UrlCheckResult, UrlVerdict } from '../src/types';

describe('UrlCache', () => {
  const sampleResult: UrlCheckResult = {
    url: 'https://example.com',
    domain: 'example.com',
    verdict: UrlVerdict.SAFE,
    confidence: 0.95,
    threats: [],
    cached: false,
    latencyMs: 50,
    timestamp: Date.now(),
  };

  beforeEach(async () => {
    urlCache.clear();
  });

  it('should return null for missing URL', async () => {
    const result = await urlCache.get('https://missing.com');
    expect(result).toBeNull();
  });

  it('should store and retrieve cached result', async () => {
    await urlCache.set('https://example.com', sampleResult);
    const cached = await urlCache.get('https://example.com');
    expect(cached).not.toBeNull();
    expect(cached!.cached).toBe(true);
    expect(cached!.verdict).toBe(UrlVerdict.SAFE);
  });

  it('should normalize URLs by stripping hash and search', async () => {
    await urlCache.set('https://example.com/page?foo=bar#section', sampleResult);
    const cached = await urlCache.get('https://example.com/page');
    expect(cached).not.toBeNull();
  });

  it('should persist and restore from storage', async () => {
    await urlCache.set('https://test.com', sampleResult);
    await urlCache.persistToStorage();
    urlCache.clear();
    await urlCache.loadFromStorage();
    const cached = await urlCache.get('https://test.com');
    expect(cached).not.toBeNull();
  });

  it('should evict oldest entry when at max capacity', async () => {
    const stats = urlCache.getStats();
    expect(stats.max).toBe(5000);
  });

  it('should handle malformed URLs gracefully', async () => {
    await urlCache.set('not-a-url', sampleResult);
    const cached = await urlCache.get('not-a-url');
    expect(cached).not.toBeNull();
  });
});
