import { Router } from "express";
import { z } from "zod";
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";
import {
  buildAuditEventsCsv,
  sha256Hex,
  signAuditManifest,
  verifyAuditManifestSignature,
} from "../services/auditBundleService.js";
import type { Prisma } from "@prisma/client";
import { parseQueryDate, isValidDate } from "../lib/parseQueryDate.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);
}
function redactMeta(meta: unknown): unknown {
  if (!meta || typeof meta !== "object") return meta;
  const blocked = new Set(["password", "smtpPassword", "token", "accessToken", "refreshToken", "secret"]);
  const out: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(meta as Record<string, unknown>)) {
    out[k] = blocked.has(k) ? "[REDACTED]" : v;
  }
  return out;
}

const auditFiltersSchema = z.object({
  module: z.string().optional(),
  action: z.string().optional(),
  actorUserId: z.string().regex(/^\d+$/).optional(),
  trainingProviderId: z.string().regex(/^\d+$/).optional(),
  sourceRef: z.string().optional(),
  from: z.string().optional(),
  to: z.string().optional(),
  format: z.enum(["json", "csv"]).optional(),
  limit: z.string().optional(),
  offset: z.string().optional(),
});

function parseAuditQuery(query: unknown) {
  return auditFiltersSchema.safeParse(query);
}

function buildWhere(projectId: bigint, q: z.infer<typeof auditFiltersSchema>) {
  const where: Prisma.SubmissionEventWhereInput = { projectId };
  if (q.module) where.module = q.module;
  if (q.action) where.action = q.action;
  if (q.actorUserId) where.actorUserId = BigInt(q.actorUserId);
  if (q.trainingProviderId) where.trainingProviderId = BigInt(q.trainingProviderId);
  if (q.sourceRef) where.sourceRef = { contains: q.sourceRef };
  if (q.from || q.to) {
    const from = parseQueryDate(q.from);
    const to = parseQueryDate(q.to);
    const createdAt: Prisma.DateTimeFilter = {};
    if (isValidDate(from)) createdAt.gte = from;
    if (isValidDate(to)) createdAt.lte = to;
    if (Object.keys(createdAt).length > 0) where.createdAt = createdAt;
  }
  return where;
}

router.get(
  "/projects/:projectId/audit/events",
  requirePermission("view:audit-trail", { 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 parsed = parseAuditQuery(req.query);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid filters", details: parsed.error.flatten() });
    const limit = parsed.data.limit ? Math.min(500, Math.max(1, Number(parsed.data.limit))) : 100;
    const offset = parsed.data.offset ? Math.max(0, Number(parsed.data.offset)) : 0;
    const where = buildWhere(projectId, parsed.data);
    const [total, rows] = await Promise.all([
      prisma.submissionEvent.count({ where }),
      prisma.submissionEvent.findMany({
        where,
        orderBy: { id: "desc" },
        skip: offset,
        take: limit,
        select: {
          id: true,
          module: true,
          action: true,
          sourceType: true,
          sourceRef: true,
          payloadHash: true,
          chainHash: true,
          prevEventId: true,
          actorUserId: true,
          trainingProviderId: true,
          trainingId: true,
          cohortId: true,
          createdAt: true,
          meta: true,
        },
      }),
    ]);
    const actorIds = [...new Set(rows.map((r) => r.actorUserId).filter((v): v is bigint => v !== null))];
    const tpIds = [...new Set(rows.map((r) => r.trainingProviderId).filter((v): v is bigint => v !== null))];
    const trainingIds = [...new Set(rows.map((r) => r.trainingId).filter((v): v is bigint => v !== null))];
    const cohortIds = [...new Set(rows.map((r) => r.cohortId).filter((v): v is bigint => v !== null))];
    const [actors, providers, trainings, cohorts] = await Promise.all([
      actorIds.length
        ? prisma.user.findMany({
            where: { id: { in: actorIds } },
            select: { id: true, name: true, email: true },
          })
        : Promise.resolve([]),
      tpIds.length
        ? prisma.trainingProvider.findMany({
            where: { id: { in: tpIds } },
            select: { id: true, name: true, tpCode: true },
          })
        : Promise.resolve([]),
      trainingIds.length
        ? prisma.training.findMany({
            where: { id: { in: trainingIds } },
            select: { id: true, title: true },
          })
        : Promise.resolve([]),
      cohortIds.length
        ? prisma.trainingCohort.findMany({
            where: { id: { in: cohortIds } },
            select: { id: true, name: true, code: true },
          })
        : Promise.resolve([]),
    ]);
    const actorNameById = new Map(actors.map((a) => [a.id.toString(), a.name || a.email || a.id.toString()]));
    const tpNameById = new Map(providers.map((p) => [p.id.toString(), p.name || p.tpCode || p.id.toString()]));
    const trainingTitleById = new Map(trainings.map((t) => [t.id.toString(), t.title || t.id.toString()]));
    const cohortNameById = new Map(cohorts.map((c) => [c.id.toString(), c.name || c.code || c.id.toString()]));
    if (parsed.data.format === "csv") {
      const hasExport = await prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: req.auth!.userId,
          role: { rolePermissions: { some: { allowed: true, permission: { key: "export:audit-trail" } } } },
        },
        select: { id: true },
      });
      if (!hasExport) return void res.status(403).json({ error: "Missing permission: export:audit-trail" });
      const csv = buildAuditEventsCsv(rows);
      res.setHeader("Content-Type", "text/csv; charset=utf-8");
      res.setHeader("Content-Disposition", `attachment; filename="audit-events-${projectId.toString()}.csv"`);
      return void res.send(csv);
    }
    res.json({
      total,
      items: rows.map((r) => ({
        id: asId(r.id),
        module: r.module,
        action: r.action,
        sourceType: r.sourceType,
        sourceRef: r.sourceRef,
        payloadHash: r.payloadHash,
        chainHash: r.chainHash,
        prevEventId: r.prevEventId ? asId(r.prevEventId) : null,
        actorUserId: r.actorUserId ? asId(r.actorUserId) : null,
        actorName: r.actorUserId ? actorNameById.get(asId(r.actorUserId)) ?? null : null,
        trainingProviderId: r.trainingProviderId ? asId(r.trainingProviderId) : null,
        trainingProviderName: r.trainingProviderId ? tpNameById.get(asId(r.trainingProviderId)) ?? null : null,
        trainingId: r.trainingId ? asId(r.trainingId) : null,
        trainingTitle: r.trainingId ? trainingTitleById.get(asId(r.trainingId)) ?? null : null,
        cohortId: r.cohortId ? asId(r.cohortId) : null,
        cohortName: r.cohortId ? cohortNameById.get(asId(r.cohortId)) ?? null : null,
        createdAt: r.createdAt.toISOString(),
        meta: redactMeta(r.meta),
      })),
    });
  },
);

router.get(
  "/projects/:projectId/audit/export-bundle",
  requirePermission("export:audit-trail", { 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 parsed = parseAuditQuery(req.query);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid filters", details: parsed.error.flatten() });
    const where = buildWhere(projectId, parsed.data);
    const rows = await prisma.submissionEvent.findMany({
      where,
      orderBy: { id: "asc" },
      take: 5000,
      select: {
        id: true,
        module: true,
        action: true,
        sourceType: true,
        sourceRef: true,
        payloadHash: true,
        chainHash: true,
        prevEventId: true,
        actorUserId: true,
        trainingProviderId: true,
        trainingId: true,
        cohortId: true,
        createdAt: true,
        meta: true,
      },
    });
    const rowsJson = rows.map((r) => ({
      id: asId(r.id),
      module: r.module,
      action: r.action,
      sourceType: r.sourceType,
      sourceRef: r.sourceRef,
      payloadHash: r.payloadHash,
      chainHash: r.chainHash,
      prevEventId: r.prevEventId ? asId(r.prevEventId) : null,
      actorUserId: r.actorUserId ? asId(r.actorUserId) : null,
      trainingProviderId: r.trainingProviderId ? asId(r.trainingProviderId) : null,
      trainingId: r.trainingId ? asId(r.trainingId) : null,
      cohortId: r.cohortId ? asId(r.cohortId) : null,
      createdAt: r.createdAt.toISOString(),
      meta: redactMeta(r.meta),
    }));
    const csv = buildAuditEventsCsv(rows);
    const eventsJson = JSON.stringify(rowsJson);
    const manifest = {
      kind: "pbps-audit-bundle",
      version: 1,
      projectId: projectId.toString(),
      generatedAt: new Date().toISOString(),
      generatedByUserId: req.auth!.userId.toString(),
      filters: {
        module: parsed.data.module ?? null,
        action: parsed.data.action ?? null,
        actorUserId: parsed.data.actorUserId ?? null,
        trainingProviderId: parsed.data.trainingProviderId ?? null,
        sourceRef: parsed.data.sourceRef ?? null,
        from: parsed.data.from ?? null,
        to: parsed.data.to ?? null,
      },
      files: {
        "events.json": { sha256: sha256Hex(eventsJson), rows: rowsJson.length },
        "events.csv": { sha256: sha256Hex(csv), rows: rowsJson.length },
      },
    };
    const signature = signAuditManifest(manifest);
    await writeAuditEvent({
      projectId,
      module: "ops",
      action: "audit_bundle_generated",
      sourceType: "audit_bundle",
      sourceRef: `${projectId.toString()}:${Date.now().toString()}`,
      payloadRaw: JSON.stringify({ rowCount: rowsJson.length }),
      meta: { rowCount: rowsJson.length, filters: manifest.filters },
      actorUserId: req.auth!.userId,
    });
    const bundle = {
      manifest,
      signature,
      files: {
        "events.json": rowsJson,
        "events.csv": csv,
      },
    };
    res.setHeader("Content-Type", "application/json; charset=utf-8");
    res.setHeader("Content-Disposition", `attachment; filename="audit-bundle-${projectId.toString()}.json"`);
    res.send(JSON.stringify(bundle));
  },
);

router.post(
  "/projects/:projectId/audit/verify-bundle",
  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 parsed = z
      .object({
        manifest: z.record(z.unknown()),
        signature: z.string().min(10),
        files: z
          .object({
            "events.json": z.union([z.string(), z.array(z.unknown())]),
            "events.csv": z.string(),
          })
          .optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid verify payload.", details: parsed.error.flatten() });

    const signatureValid = verifyAuditManifestSignature(parsed.data.manifest, parsed.data.signature);
    const checks: Array<{ file: string; expected: string | null; actual: string | null; ok: boolean }> = [];
    const manifestFiles =
      parsed.data.manifest.files && typeof parsed.data.manifest.files === "object"
        ? (parsed.data.manifest.files as Record<string, { sha256?: string }>)
        : {};

    if (parsed.data.files) {
      const eventsJsonRaw =
        typeof parsed.data.files["events.json"] === "string"
          ? parsed.data.files["events.json"]
          : JSON.stringify(parsed.data.files["events.json"]);
      const eventsCsvRaw = parsed.data.files["events.csv"];
      const expectedJson = manifestFiles["events.json"]?.sha256 ?? null;
      const expectedCsv = manifestFiles["events.csv"]?.sha256 ?? null;
      const actualJson = sha256Hex(eventsJsonRaw);
      const actualCsv = sha256Hex(eventsCsvRaw);
      checks.push({ file: "events.json", expected: expectedJson, actual: actualJson, ok: expectedJson === actualJson });
      checks.push({ file: "events.csv", expected: expectedCsv, actual: actualCsv, ok: expectedCsv === actualCsv });
    }
    const filesOk = checks.every((c) => c.ok);
    await writeAuditEvent({
      projectId,
      module: "ops",
      action: "audit_bundle_verified",
      sourceType: "audit_bundle",
      sourceRef: `${projectId.toString()}:${Date.now().toString()}`,
      payloadRaw: JSON.stringify({ signatureValid, filesOk }),
      meta: { signatureValid, filesOk, checks },
      actorUserId: req.auth!.userId,
    });

    res.json({ ok: signatureValid && filesOk, signatureValid, filesOk, checks });
  },
);

router.get(
  "/projects/:projectId/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,
    });
  },
);

export default router;

