/**
 * AUDIT-2 #18 smoke — SLA Tracking feature fully removed.
 *
 * Background (operator request, 2026-05-24): the SLA Tracking sidebar
 * menu + page + Executive Dashboard widget were unused (0 SLATarget +
 * 0 SLAReport rows in live dev DB). Operator asked for full removal
 * with care not to break other sections.
 *
 * This smoke statically asserts:
 *   1. All deleted files are gone (no orphan imports possible).
 *   2. schema.prisma no longer defines SLATarget / SLAReport.
 *   3. The migration that drops SLAReport + SLATarget exists with
 *      leaves-first ordering.
 *   4. Sidebar, search registry, Executive Dashboard, ExportBoardReport
 *      no longer reference SLA fields. Reasonable proxy for "no
 *      dangling reads of metrics.overview.slaCompliance / slaStatus".
 *   5. Reports/executive route returns no SLA keys in its response.
 *   6. src/types/models.ts no longer exports SLATarget / SLAScorecard.
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync, existsSync } from 'fs';
import path from 'path';

const ROOT = path.resolve(__dirname, '../..');

function read(rel: string): string {
    try { return readFileSync(path.join(ROOT, rel), 'utf8'); }
    catch (err) { fail(`read ${rel}`, String(err)); }
}

function assertGone(label: string, rel: string): void {
    if (existsSync(path.join(ROOT, rel))) fail(label, `file still exists: ${rel}`);
    ok(label);
}

function assertNotPresent(label: string, src: string, needle: string | RegExp): void {
    const re = typeof needle === 'string'
        ? new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
        : needle;
    if (re.test(src)) fail(label, `pattern still present: ${String(needle)}`);
    ok(label);
}

function assertPresent(label: string, src: string, needle: string | RegExp): void {
    const re = typeof needle === 'string'
        ? new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
        : needle;
    if (!re.test(src)) fail(label, `missing required pattern: ${String(needle)}`);
    ok(label);
}

function main(): void {
    // 1. Deleted files
    assertGone('audit2-18: /api/sla/reports gone', 'src/app/api/sla/reports/route.ts');
    assertGone('audit2-18: /api/sla/targets gone', 'src/app/api/sla/targets/route.ts');
    // 2026-06-03: /sla now hosts the NEW vendor-attributed SLA view (renders
    // VendorList, backed by the Vendor model — NOT the removed SLATarget/
    // SLAReport module). The legacy SLADashboard component stays deleted.
    assertGone('audit2-18: SLADashboard gone', 'src/components/sla/SLADashboard.tsx');
    assertGone('audit2-18: SLAEditor gone', 'src/components/sla/SLAEditor.tsx');
    assertGone('audit2-18: SLAGauge gone', 'src/components/sla/SLAGauge.tsx');
    assertGone('audit2-18: SLAStatusWidget gone', 'src/components/executive/SLAStatusWidget.tsx');
    assertGone('audit2-18: sla-calculator service gone', 'src/lib/services/sla-calculator.service.ts');

    // 2. schema.prisma — no SLATarget / SLAReport models
    const schema = read('prisma/schema.prisma');
    assertNotPresent('audit2-18: SLATarget model removed from schema', schema, /^model SLATarget /m);
    assertNotPresent('audit2-18: SLAReport model removed from schema', schema, /^model SLAReport /m);
    assertNotPresent('audit2-18: User.slaTargetsCreated relation removed', schema, /slaTargetsCreated\s+SLATarget/);
    assertNotPresent('audit2-18: Country.slaTargets relation removed', schema, /slaTargets\s+SLATarget/);

    // 3. Migration exists with leaves-first DROP order (SLAReport before SLATarget)
    const migration = read('prisma/migrations/20260524000002_audit2_18_drop_sla/migration.sql');
    assertPresent('audit2-18: migration drops SLAReport', migration, /DROP TABLE\s+`SLAReport`/);
    assertPresent('audit2-18: migration drops SLATarget', migration, /DROP TABLE\s+`SLATarget`/);
    const dropReportIdx = migration.indexOf('DROP TABLE `SLAReport`');
    const dropTargetIdx = migration.indexOf('DROP TABLE `SLATarget`');
    if (dropReportIdx === -1 || dropTargetIdx === -1 || dropReportIdx >= dropTargetIdx) {
        fail('audit2-18: leaves-first', 'SLAReport must be dropped BEFORE SLATarget (FK leaves-first)');
    }
    ok('audit2-18: migration drops SLAReport before SLATarget (leaves-first)');

    // 4. Search registry + dashboards no longer reference the OLD SLA fields.
    // 2026-06-03: the sidebar now intentionally carries a NEW "SLA" NavItem ->
    // /sla (the vendor-attributed SLA view), so the old "no /sla href / no SLA
    // NavItem" assertions are retired. The removed generic module is still
    // guarded by the SLATarget/SLAReport + legacy-component checks above/below.
    const search = read('src/app/api/search/route.ts');
    assertNotPresent('audit2-18: Search registry has no SLA Compliance entry', search, /title:\s*["']SLA Compliance["']/);

    // audit3-followup (2026-05-30): the legacy Executive Dashboard components
    // (ExecutiveDashboard.tsx + ExportBoardReport.tsx) were removed in the
    // executive redesign, so their SLA widgets are gone by deletion. The new
    // /executive UI (src/app/executive/) and its data contract have no SLA
    // concept at all.
    assertGone('audit2-18: legacy ExecutiveDashboard removed (SLA widget gone)', 'src/components/executive/ExecutiveDashboard.tsx');
    assertGone('audit2-18: legacy ExportBoardReport removed (SLA read gone)', 'src/components/executive/ExportBoardReport.tsx');
    assertNotPresent('audit2-18: new executive data contract has no SLA', read('src/lib/executive/types.ts'), /sla/i);

    // 5. /api/reports/executive route — no SLA keys in response.
    // Strip line comments first so that explanatory removal-marker
    // comments don't trip the literal-string assertions.
    const execRouteRaw = read('src/app/api/reports/executive/route.ts');
    const execRoute = execRouteRaw.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
    assertNotPresent('audit2-18: executive route does not query prisma.sLATarget', execRoute, /prisma\.sLATarget/);
    assertNotPresent('audit2-18: executive route does not return slaCompliance', execRoute, /slaCompliance:\s/);
    assertNotPresent('audit2-18: executive route does not return slaStatus', execRoute, /slaStatus:\s\{/);
    assertNotPresent('audit2-18: executive route does not return slaTrend', execRoute, /slaTrend:\s/);

    // 6. types/models.ts — SLATarget + SLAScorecard interfaces removed
    const types = read('src/types/models.ts');
    assertNotPresent('audit2-18: types/models.ts has no SLATarget interface', types, /^export interface SLATarget /m);
    assertNotPresent('audit2-18: types/models.ts has no SLAScorecard interface', types, /^export interface SLAScorecard /m);

    ok('audit2-18-sla-removal', 'SLA Tracking feature fully removed (8 files + 2 models + relations + types)');
}

main();
