import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { audit, loadTokens } from '../audit.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const tokensFile = path.resolve(__dirname, '../../../tokens.json');

function writeFile(root: string, rel: string, content: string): void {
  const abs = path.join(root, rel);
  mkdirSync(path.dirname(abs), { recursive: true });
  writeFileSync(abs, content, 'utf-8');
}

async function run(tmpDir: string) {
  const tokens = await loadTokens(tokensFile);
  return audit(
    { projectPath: tmpDir, mode: 'audit', rules: ['R27'], paths: [], urls: [], regenerateThreshold: 0 },
    tokens,
  );
}

describe('R27-responsive-datatable', () => {
  let tmpDir: string;
  beforeEach(() => { tmpDir = mkdtempSync(path.join(tmpdir(), 'ui-polish-r27-')); });
  afterEach(() => { rmSync(tmpDir, { recursive: true, force: true }); });

  it('FIRES (warning) — ListPage renders a bare <DataTable> (generic form)', async () => {
    writeFile(tmpDir, 'src/pages/test/FoosListPage.tsx', `
export function FoosListPage() {
  return (<DataTable<Foo> data={[]} columns={[]} />);
}
`);
    const report = await run(tmpDir);
    expect(report.findings).toHaveLength(1);
    expect(report.findings[0].ruleId).toBe('R27-responsive-datatable');
    expect(report.findings[0].severity).toBe('warning');
    expect(report.findings[0].message).toContain('ResponsiveDataTable');
  });

  it('SILENT — ListPage uses <ResponsiveDataTable> (the wrapper)', async () => {
    writeFile(tmpDir, 'src/pages/test/FoosListPage.tsx', `
import { ResponsiveDataTable } from '@/components/ui/ResponsiveDataTable';
export function FoosListPage() {
  return (<ResponsiveDataTable<Foo> data={[]} columns={[]} />);
}
`);
    const report = await run(tmpDir);
    expect(report.findings).toHaveLength(0);
  });

  it('SILENT — a bare <DataTable> on a non-ListPage is not flagged (gated to *ListPage.tsx)', async () => {
    writeFile(tmpDir, 'src/pages/test/FooDetailPage.tsx', `
export function FooDetailPage() {
  return (<DataTable<Foo> data={[]} columns={[]} />);
}
`);
    const report = await run(tmpDir);
    expect(report.findings).toHaveLength(0);
  });

  it('SILENT — ListPage with no table at all', async () => {
    writeFile(tmpDir, 'src/pages/test/FoosListPage.tsx', `
export function FoosListPage() {
  return (<div>nothing tabular here</div>);
}
`);
    const report = await run(tmpDir);
    expect(report.findings).toHaveLength(0);
  });
});
