/**
 * PR-23 smoke — audit-log export writes CSV + CEF and respects retention.
 *
 * Run: npx tsx scripts/smoke/pr23-audit-export.ts
 */
import './_lib';
import { ok, fail } from './_lib';
import { AuditExportService, csvEscape, cefEscape, entryToCefLine } from '../../src/lib/services/audit-export.service';
import fs from 'fs/promises';
import path from 'path';
import os from 'os';

async function main(): Promise<void> {
    if (csvEscape('a,b') !== '"a,b"') fail('PR-23 csv', 'CSV escaping broken');
    ok('CSV escaping quotes commas');

    if (cefEscape('a|b') !== 'a\\|b') fail('PR-23 cef', 'CEF escaping broken');
    ok('CEF escaping escapes pipes');

    const entry = {
        id: 1,
        createdAt: new Date('2026-05-22T10:00:00Z'),
        action: 'DELETE',
        resource: 'Monitor',
        resourceId: '7',
        details: null,
        user: { email: 'admin@example.com', name: null },
    };
    if (!entryToCefLine(entry).startsWith('CEF:0|EvidenceAction|UptimeSentinel|1.0|')) {
        fail('PR-23 cef-header', 'CEF line missing prefix');
    }
    ok('CEF line carries the EvidenceAction|UptimeSentinel header');

    // Live write to a tmp dir
    const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'pr23-smoke-'));
    const mockPrisma = {
        auditLog: {
            findMany: async () => [entry],
        },
    };
    const svc = new AuditExportService({
        prisma: mockPrisma as never,
        outputDir: tmp,
        now: () => new Date('2026-05-22T18:00:00Z'),
    });
    const result = await svc.exportDay(new Date('2026-05-22T18:00:00Z'));
    if (!result.written || result.rows !== 1) fail('PR-23 export', `unexpected result: ${JSON.stringify(result)}`);
    const csv = await fs.readFile(path.join(tmp, 'auditlog-2026-05-22.csv'), 'utf8');
    if (!csv.includes('admin@example.com,DELETE,Monitor')) fail('PR-23 csv-content', 'CSV missing expected row');
    ok('exportDay writes CSV + CEF and returns rows count');

    await fs.rm(tmp, { recursive: true, force: true });

    ok('PR-23 audit-export smoke', 'export + escaping + idempotency contract holds');
}

main().catch((e) => fail('PR-23 crashed', String(e)));
