import { Router } from "express";
import { Prisma } from "@prisma/client";
import { prisma } from "../prisma.js";
import { requireAuth, type AuthedRequest } from "../middleware/auth.js";
import { requirePermission } from "../middleware/permissions.js";
import { hasProjectAccess as hasProjectAccessPolicy } from "../services/scopePolicy.js";
import { verifyAuditChain, writeAuditEvent } from "../services/auditEventService.js";

const router = Router();
router.use(requireAuth);

function asId(v: bigint) {
  return v.toString();
}

async function hasProjectAccess(projectId: bigint, userId: bigint) {
  return hasProjectAccessPolicy(prisma, projectId, userId);
}

type OrphanAttendanceRow = {
  id: bigint;
  trainee_id: bigint;
  session_date: Date;
  status: string;
  training_provider_id: bigint;
  training_id: bigint;
  batch_id: bigint;
};

async function countOrphanAttendanceRows(projectId: bigint): Promise<number> {
  const rows = await prisma.$queryRaw<Array<{ c: bigint }>>(Prisma.sql`
    SELECT COUNT(*) AS c
    FROM trainee_attendance_days tad
    LEFT JOIN trainees t ON t.id = tad.trainee_id
    WHERE tad.project_id = ${projectId} AND t.id IS NULL
  `);
  return Number(rows[0]?.c ?? 0);
}

async function sampleOrphanAttendanceRows(projectId: bigint, limit = 50): Promise<OrphanAttendanceRow[]> {
  return prisma.$queryRaw<OrphanAttendanceRow[]>(Prisma.sql`
    SELECT tad.id, tad.trainee_id, tad.session_date, tad.status, tad.training_provider_id, tad.training_id, tad.batch_id
    FROM trainee_attendance_days tad
    LEFT JOIN trainees t ON t.id = tad.trainee_id
    WHERE tad.project_id = ${projectId} AND t.id IS NULL
    ORDER BY tad.session_date DESC, tad.id DESC
    LIMIT ${limit}
  `);
}

async function countPendingResubmissions(projectId: bigint) {
  const latestRequests = await prisma.submissionEvent.findMany({
    where: { projectId, module: "outcomes", action: "resubmission_requested" },
    orderBy: { id: "desc" },
    select: { id: true },
    take: 300,
  });
  let pending = 0;
  for (const reqRow of latestRequests) {
    const decision = await prisma.submissionEvent.findFirst({
      where: {
        projectId,
        module: "outcomes",
        action: { in: ["resubmission_approved", "resubmission_rejected", "resubmission_consumed"] },
        sourceRef: reqRow.id.toString(),
      },
      orderBy: { id: "desc" },
      select: { action: true },
    });
    if (!decision || decision.action === "resubmission_approved") pending += 1;
  }
  return pending;
}

router.get(
  "/projects/:projectId/ops/audit-integrity",
  requirePermission("verify:audit-integrity", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const out = await verifyAuditChain(projectId, 10000);
    res.json({
      checked: out.checked,
      validated: out.validated,
      skippedLegacy: out.skippedLegacy,
      issues: out.issues,
      issuesByReason: out.issuesByReason,
      ok: out.issues.length === 0,
      computedAt: new Date().toISOString(),
    });
  },
);

router.get(
  "/projects/:projectId/ops/data-quality",
  requirePermission("admin:settings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });

    const [missingScopeCount, cohortMismatchCount, missingBatchCount, missingScopeSample, cohortMismatchSample, missingBatchSample] = await Promise.all([
      prisma.trainee.count({
        where: { projectId, OR: [{ locationId: null }, { trainingDurationId: null }] },
      }),
      prisma.trainee.count({
        where: {
          projectId,
          cohortId: null,
          trainingId: { not: null },
        },
      }),
      prisma.trainee.count({ where: { projectId, batchId: null } }),
      prisma.trainee.findMany({
        where: { projectId, OR: [{ locationId: null }, { trainingDurationId: null }] },
        take: 50,
        orderBy: { id: "desc" },
        select: {
          id: true,
          traineeUniqueId: true,
          firstName: true,
          fatherName: true,
          trainingId: true,
          cohortId: true,
          batchId: true,
          locationId: true,
          trainingDurationId: true,
        },
      }),
      prisma.trainee.findMany({
        where: {
          projectId,
          cohortId: null,
          trainingId: { not: null },
        },
        take: 50,
        orderBy: { id: "desc" },
        select: {
          id: true,
          traineeUniqueId: true,
          firstName: true,
          fatherName: true,
          trainingId: true,
          cohortId: true,
          batchId: true,
          training: { select: { id: true, title: true } },
        },
      }),
      prisma.trainee.findMany({
        where: { projectId, batchId: null },
        take: 50,
        orderBy: { id: "desc" },
        select: {
          id: true,
          traineeUniqueId: true,
          firstName: true,
          fatherName: true,
          trainingId: true,
          cohortId: true,
        },
      }),
    ]);

    const dupPhones = await prisma.trainee.groupBy({
      by: ["phonePrimary"],
      where: { projectId, phonePrimary: { not: null } },
      _count: { _all: true },
      having: { phonePrimary: { _count: { gt: 1 } } },
      orderBy: { phonePrimary: "asc" },
      take: 50,
    });

    const [orphanAttendanceCount, orphanAttendanceSample] = await Promise.all([
      countOrphanAttendanceRows(projectId),
      sampleOrphanAttendanceRows(projectId, 50),
    ]);

    res.json({
      computedAt: new Date().toISOString(),
      totals: {
        traineesMissingLocationOrDuration: missingScopeCount,
        traineesCohortMismatch: cohortMismatchCount,
        traineesMissingDeliveryBatch: missingBatchCount,
        duplicatePhonePrimaryGroups: dupPhones.length,
        orphanAttendanceRows: orphanAttendanceCount,
      },
      samples: {
        traineesMissingLocationOrDuration: missingScopeSample.map((t) => ({
          id: asId(t.id),
          traineeUniqueId: t.traineeUniqueId,
          name: `${t.firstName ?? ""} ${t.fatherName ?? ""}`.trim() || null,
          trainingId: t.trainingId ? asId(t.trainingId) : null,
          cohortId: t.cohortId ? asId(t.cohortId) : null,
          batchId: t.batchId ? asId(t.batchId) : null,
          locationId: t.locationId ? asId(t.locationId) : null,
          trainingDurationId: t.trainingDurationId ? asId(t.trainingDurationId) : null,
        })),
        traineesCohortMismatch: cohortMismatchSample.map((t) => ({
          id: asId(t.id),
          traineeUniqueId: t.traineeUniqueId,
          name: `${t.firstName ?? ""} ${t.fatherName ?? ""}`.trim() || null,
          trainingId: t.trainingId ? asId(t.trainingId) : null,
          cohortId: t.cohortId ? asId(t.cohortId) : null,
          batchId: t.batchId ? asId(t.batchId) : null,
          trainingTitle: t.training?.title ?? null,
          issueHint: "Trainee is missing cohort linkage.",
        })),
        traineesMissingDeliveryBatch: missingBatchSample.map((t) => ({
          id: asId(t.id),
          traineeUniqueId: t.traineeUniqueId,
          name: `${t.firstName ?? ""} ${t.fatherName ?? ""}`.trim() || null,
          trainingId: t.trainingId ? asId(t.trainingId) : null,
          cohortId: t.cohortId ? asId(t.cohortId) : null,
        })),
        duplicatePhonePrimary: dupPhones.map((g) => ({
          phonePrimary: g.phonePrimary,
          count: typeof (g as any)._count?._all === "number" ? (g as any)._count._all : 0,
        })),
        orphanAttendanceRows: orphanAttendanceSample.map((r) => ({
          id: asId(r.id),
          traineeId: asId(r.trainee_id),
          sessionDate: r.session_date.toISOString().slice(0, 10),
          status: r.status,
          trainingProviderId: asId(r.training_provider_id),
          trainingId: asId(r.training_id),
          batchId: asId(r.batch_id),
        })),
      },
      notes: [
        "These checks are intentionally lightweight for pilot operations and meant to highlight common integrity risks.",
        "Delivery batch is required on trainees; missing batch_id blocks attendance and timeline rollups.",
        "Orphan attendance rows reference deleted trainees. They do not affect the main attendance KPI rate (which only counts current roster trainees) but can inflate daily trend charts.",
        "For any exception cleanup, fix root cause (scope mapping, cohort assignment, imports) before bulk editing records.",
      ],
    });
  },
);

router.post(
  "/projects/:projectId/ops/data-quality/repair-scope-fields",
  requirePermission("admin:settings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });

    const candidates = await prisma.trainee.findMany({
      where: { projectId, OR: [{ locationId: null }, { trainingDurationId: null }] },
      select: {
        id: true,
        trainingId: true,
        cohortId: true,
        locationId: true,
        trainingDurationId: true,
        training: { select: { id: true, locationId: true, trainingDurationId: true } },
        cohort: { select: { id: true, locationId: true, trainingId: true } },
      },
      take: 5000,
      orderBy: { id: "asc" },
    });

    let repaired = 0;
    let skipped = 0;
    const skippedItems: Array<{ traineeId: string; reason: string }> = [];

    for (const t of candidates) {
      const tr = t.training;
      if (!tr) {
        skipped += 1;
        skippedItems.push({ traineeId: asId(t.id), reason: "Missing training relation." });
        continue;
      }
      const resolvedDurationId = tr.trainingDurationId ?? null;
      const resolvedLocationId = t.cohort?.locationId ?? tr.locationId ?? null;
      if (!resolvedLocationId || !resolvedDurationId) {
        skipped += 1;
        skippedItems.push({
          traineeId: asId(t.id),
          reason: `Resolved fields incomplete (locationId=${resolvedLocationId ? "set" : "null"}, trainingDurationId=${
            resolvedDurationId ? "set" : "null"
          }).`,
        });
        continue;
      }
      await prisma.trainee.update({
        where: { id: t.id },
        data: {
          locationId: resolvedLocationId,
          trainingDurationId: resolvedDurationId,
        },
      });
      repaired += 1;
    }

    res.json({
      ok: true,
      counts: { scanned: candidates.length, repaired, skipped },
      skipped: skippedItems.slice(0, 200),
      note: "Safe repair only backfills fields from current training/cohort relationships.",
    });
  },
);

router.post(
  "/projects/:projectId/ops/data-quality/repair-orphan-attendance",
  requirePermission("admin:settings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) {
      return void res.status(403).json({ error: "No access." });
    }

    const before = await countOrphanAttendanceRows(projectId);
    if (before === 0) {
      return res.json({ ok: true, deleted: 0, note: "No orphan attendance rows found." });
    }

    const deleted = await prisma.$executeRaw(Prisma.sql`
      DELETE tad FROM trainee_attendance_days tad
      LEFT JOIN trainees t ON t.id = tad.trainee_id
      WHERE tad.project_id = ${projectId} AND t.id IS NULL
    `);

    await writeAuditEvent({
      projectId,
      module: "domain",
      action: "orphan_attendance_removed",
      sourceType: "ops",
      sourceRef: "data-quality",
      actorUserId: req.auth!.userId,
      meta: { deletedRows: Number(deleted), orphanCountBefore: before },
    });

    res.json({
      ok: true,
      deleted: Number(deleted),
      note: "Removed attendance rows whose trainee no longer exists. Main attendance KPI uses current roster only.",
    });
  },
);

router.get(
  "/projects/:projectId/ops/risk-monitor",
  requirePermission("admin:settings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });

    const staleBefore = new Date();
    staleBefore.setUTCDate(staleBefore.getUTCDate() - 14);
    const reviewLagBefore = new Date();
    reviewLagBefore.setUTCDate(reviewLagBefore.getUTCDate() - 7);

    const [openVerificationRuns14d, pendingActivityReviews7d, failedOutcomeImports30d, unresolvedResubmissions] = await Promise.all([
      prisma.verificationSampleRun.count({
        where: { projectId, status: "open", drawnAt: { lt: staleBefore } },
      }),
      prisma.tpActivitySubmission.count({
        where: { projectId, status: "submitted", submittedAt: { lt: reviewLagBefore } },
      }),
      prisma.outcomeReportBatch.count({
        where: { projectId, status: "failed", createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } },
      }),
      countPendingResubmissions(projectId),
    ]);

    res.json({
      computedAt: new Date().toISOString(),
      risks: {
        openVerificationRuns14d,
        pendingActivityReviews7d,
        failedOutcomeImports30d,
        unresolvedResubmissions,
      },
      notes: [
        "Pilot mode: alerts are informational only and do not block operations.",
        "Use this report weekly for provider follow-up and reviewer workload balancing.",
      ],
    });
  },
);

router.get(
  "/projects/:projectId/ops/executive-pack",
  requirePermission("admin:settings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });

    const [providers, trainings, trainees, outcomesProcessed, verificationRuns, grievances] = await Promise.all([
      prisma.trainingProvider.count({ where: { projectId } }),
      prisma.training.count({ where: { projectId } }),
      prisma.trainee.count({ where: { projectId } }),
      prisma.outcomeReportBatch.count({ where: { projectId, status: "processed" } }),
      prisma.verificationSampleRun.count({ where: { projectId } }),
      prisma.feedbackThread.count({ where: { projectId } }),
    ]);

    res.json({
      generatedAt: new Date().toISOString(),
      projectId: asId(projectId),
      snapshot: {
        providers,
        trainings,
        trainees,
        outcomesProcessed,
        verificationRuns,
        grievances,
      },
      sections: [
        "Operations coverage",
        "Outcomes and verification volume",
        "Feedback and grievance volume",
      ],
    });
  },
);

export default router;

