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 } from "../services/scopePolicy.js";
import { trackedRosterRoleFilter } from "../services/traineeRoster.js";
import { Prisma } from "@prisma/client";
import { parseQueryDate, isValidDate } from "../lib/parseQueryDate.js";

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

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

const activityQuerySchema = z.object({
  trainingProviderId: z.string().regex(/^\d+$/).optional(),
  from: z.string().optional(),
  to: z.string().optional(),
  rosterOnly: z.enum(["true", "false"]).optional(),
});

async function detectRegistrationWindow(projectId: bigint): Promise<{ from: Date | null; to: Date | null }> {
  const lastOpen = await prisma.submissionEvent.findFirst({
    where: { projectId, action: "project_registration_opened" },
    orderBy: { createdAt: "desc" },
  });
  if (!lastOpen) return { from: null, to: null };

  const closeAfterOpen = await prisma.submissionEvent.findFirst({
    where: {
      projectId,
      action: "project_registration_closed",
      createdAt: { gt: lastOpen.createdAt },
    },
    orderBy: { createdAt: "asc" },
  });

  return {
    from: lastOpen.createdAt,
    to: closeAfterOpen?.createdAt ?? new Date(),
  };
}

function traineeWhere(
  projectId: bigint,
  trainingProviderId: bigint | undefined,
  rosterOnly: boolean,
): Prisma.TraineeWhereInput {
  return {
    projectId,
    ...(trainingProviderId ? { trainingProviderId } : {}),
    ...(rosterOnly ? { rosterRole: trackedRosterRoleFilter() } : {}),
  };
}

router.get(
  "/projects/:projectId/monitor/registration-activity",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  requirePermission("view:audit-trail", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(prisma, projectId, req.auth!.userId))) {
      return void res.status(403).json({ error: "No access." });
    }

    const parsed = activityQuerySchema.safeParse(req.query);
    if (!parsed.success) {
      return void res.status(400).json({ error: "Invalid filters", details: parsed.error.flatten() });
    }

    const trainingProviderId = parsed.data.trainingProviderId
      ? BigInt(parsed.data.trainingProviderId)
      : undefined;
    const rosterOnly = parsed.data.rosterOnly !== "false";

    const detected = await detectRegistrationWindow(projectId);
    const from = parseQueryDate(parsed.data.from) ?? detected.from;
    const to = parseQueryDate(parsed.data.to) ?? detected.to;
    const windowSource = parsed.data.from || parsed.data.to ? "manual" : detected.from ? "audit" : "none";
    const hasWindow = isValidDate(from) && isValidDate(to);

    const baseWhere = traineeWhere(projectId, trainingProviderId, rosterOnly);

    const [registeredBefore, registeredDuring, currentTotal, dailyRows, auditRows] = await Promise.all([
      isValidDate(from)
        ? prisma.trainee.count({ where: { ...baseWhere, createdAt: { lt: from } } })
        : prisma.trainee.count({ where: baseWhere }),
      hasWindow
        ? prisma.trainee.count({
            where: { ...baseWhere, createdAt: { gte: from, lte: to } },
          })
        : 0,
      prisma.trainee.count({ where: baseWhere }),
      hasWindow
        ? prisma.$queryRaw<Array<{ day: Date; count: bigint }>>`
            SELECT DATE(created_at) AS day, COUNT(*) AS count
            FROM trainees
            WHERE project_id = ${projectId}
              ${trainingProviderId ? Prisma.sql`AND training_provider_id = ${trainingProviderId}` : Prisma.empty}
              ${rosterOnly ? Prisma.sql`AND roster_role IN ('active', 'reserve')` : Prisma.empty}
              AND created_at >= ${from}
              AND created_at <= ${to}
            GROUP BY DATE(created_at)
            ORDER BY day ASC
          `
        : Promise.resolve([]),
      hasWindow
        ? prisma.submissionEvent.findMany({
            where: {
              projectId,
              module: "domain",
              action: { in: ["trainee_deleted", "trainee_imported", "trainee_created"] },
              createdAt: { gte: from, lte: to },
              ...(trainingProviderId
                ? {
                    OR: [{ action: "trainee_imported" }, { trainingProviderId }],
                  }
                : {}),
            },
            orderBy: { createdAt: "desc" },
            select: {
              id: true,
              action: true,
              sourceType: true,
              sourceRef: true,
              actorUserId: true,
              trainingProviderId: true,
              createdAt: true,
              meta: true,
            },
          })
        : prisma.submissionEvent.findMany({
            where: {
              projectId,
              module: "domain",
              action: { in: ["trainee_deleted", "trainee_imported", "trainee_created"] },
              ...(trainingProviderId
                ? {
                    OR: [{ action: "trainee_imported" }, { trainingProviderId }],
                  }
                : {}),
            },
            orderBy: { createdAt: "desc" },
            take: 500,
            select: {
              id: true,
              action: true,
              sourceType: true,
              sourceRef: true,
              actorUserId: true,
              trainingProviderId: true,
              createdAt: true,
              meta: true,
            },
          }),
    ]);

    const actorIds = [...new Set(auditRows.map((r) => r.actorUserId).filter((v): v is bigint => v !== null))];
    const tpIds = [...new Set(auditRows.map((r) => r.trainingProviderId).filter((v): v is bigint => v !== null))];
    const [actors, providers] = 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 },
          })
        : 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]));

    // Correlate import audit events with trainee creation counts (±3 minutes).
    const importCorrelations = await Promise.all(
      auditRows
        .filter((e) => e.action === "trainee_imported")
        .map(async (e) => {
          const windowStart = new Date(e.createdAt.getTime() - 3 * 60 * 1000);
          const windowEnd = new Date(e.createdAt.getTime() + 3 * 60 * 1000);
          const correlatedCount = await prisma.trainee.count({
            where: {
              ...baseWhere,
              createdAt: { gte: windowStart, lte: windowEnd },
            },
          });
          return { eventId: asId(e.id), correlatedCount };
        }),
    );
    const correlatedByEventId = new Map(importCorrelations.map((c) => [c.eventId, c.correlatedCount]));

    res.json({
      window: {
        from: from?.toISOString() ?? null,
        to: to?.toISOString() ?? null,
        source: windowSource,
      },
      summary: {
        registeredBefore,
        registeredDuring,
        currentTotal,
        netChangeDuring: registeredDuring,
      },
      dailyBreakdown: dailyRows.map((r) => ({
        date: r.day instanceof Date ? r.day.toISOString().slice(0, 10) : String(r.day).slice(0, 10),
        count: Number(r.count),
      })),
      auditTimeline: auditRows.map((e) => ({
        id: asId(e.id),
        createdAt: e.createdAt.toISOString(),
        action: e.action,
        sourceType: e.sourceType,
        sourceRef: e.sourceRef,
        actorUserId: e.actorUserId ? asId(e.actorUserId) : null,
        actorName: e.actorUserId ? actorNameById.get(asId(e.actorUserId)) ?? null : null,
        trainingProviderId: e.trainingProviderId ? asId(e.trainingProviderId) : null,
        trainingProviderName: e.trainingProviderId ? tpNameById.get(asId(e.trainingProviderId)) ?? null : null,
        correlatedImportCount:
          e.action === "trainee_imported" ? correlatedByEventId.get(asId(e.id)) ?? null : null,
        meta: e.meta,
      })),
    });
  },
);

export default router;
