import { describe, it, expect } from 'vitest';
import { execSync } from 'node:child_process';
import { resolve } from 'node:path';
import { ERROR_COPY, lookupErrorCopy } from '../error-copy';

const repoRoot = resolve(__dirname, '../../../..');

function discoverCodes(): Set<string> {
  const out = execSync(
    `grep -rohE "ok: false, error: '[^']+'" extension/src/service-worker/ \
       --include="*.ts" --exclude-dir=__tests__`,
    { cwd: repoRoot, encoding: 'utf-8' },
  );
  const codes = new Set<string>();
  for (const line of out.split('\n')) {
    const m = line.match(/error: '([^']+)'/);
    if (m) codes.add(m[1]);
  }
  return codes;
}

describe('ERROR_COPY', () => {
  it('contains an entry for every error code returned by the service worker', () => {
    const discovered = discoverCodes();
    expect(discovered.size).toBeGreaterThan(0);
    const missing: string[] = [];
    for (const code of discovered) {
      if (!ERROR_COPY[code]) missing.push(code);
    }
    expect(missing).toEqual([]);
  });

  it('lookupErrorCopy returns the mapped entry for known codes', () => {
    const copy = lookupErrorCopy('vault_locked');
    expect(copy.title).toBe('Vault locked');
    expect(copy.body).toMatch(/unlock/i);
  });

  it('lookupErrorCopy falls back to a generic shape for unknown codes', () => {
    const copy = lookupErrorCopy('made_up_code_xyz');
    expect(copy.title).toBe('Something went wrong');
    expect(copy.body).toContain('made_up_code_xyz');
  });
});
