import { Router } from "express";
import { z } from "zod";
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 {
  isScheduledSessionDate,
  isoWeekdayMonToSun,
  normalizeAttendanceSessionDate,
  parseSessionWeekdays,
  sessionDateKey,
  scheduledSessionDates,
  type TrainingDateRange,
} from "../services/attendanceCalendar.js";
import {
  computeAttendancePresentPossible,
  computeAttendancePresentPossibleForTrainingScope,
  computeTraineeAttendanceRatesForProvider,
} from "../services/attendanceRollup.js";
import {
  computeAttendanceSubmissionCoverageByTp,
  computeAttendanceSubmissionCoverageBreakdown,
} from "../services/attendanceCoverageSlots.js";
import { fetchAttendanceDailySeries } from "../services/attendanceDailySeries.js";
import {
  eligibleSessionKeysForTrainee,
  traineeBreakdownExcludedKeysForDeliveryBatch,
  type AttendanceBreakdownRow,
} from "../services/attendanceEligibility.js";
import {
  exemptPeriodMeta,
  filterScheduledDatesExcludingExemptPeriod,
  firstAttendanceTrackingDay,
  isSessionDateExempt,
  loadAttendanceExemptDaysFromStart,
} from "../services/attendanceExemptPeriod.js";
import { rosterRoleReceivesAttendanceCapture } from "../services/traineeRoster.js";
import {
  hasProjectAccess as hasProjectAccessPolicy,
  resolveProjectScope as resolveProjectScopePolicy,
  assertTpAssigned,
  assertDeliveryScope,
  enforceProviderScope,
  isDeliveryScopeAllowed,
} from "../services/scopePolicy.js";
import { resolveTraineeDeliveryBatchId, resolveTrainingScope } from "../services/trainingScopeGuards.js";
import { writeAuditEvent } from "../services/auditEventService.js";

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

async function hasProjectAccess(projectId: bigint, userId: bigint): Promise<boolean> {
  return hasProjectAccessPolicy(prisma, projectId, userId);
}
async function resolveScope(projectId: bigint, userId: bigint) {
  return resolveProjectScopePolicy(prisma, projectId, userId);
}

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

/** Parse YYYY-MM-DD as UTC midnight for @db.Date storage and queries. */
function toDbDateOnly(yyyyMmDd: string): Date {
  return new Date(`${yyyyMmDd}T00:00:00.000Z`);
}

function parseAttendanceImportDate(raw: string): { date: Date; normalized: string } | null {
  const normalized = normalizeAttendanceSessionDate(raw);
  if (!normalized) return null;
  const date = toDbDateOnly(normalized);
  return Number.isNaN(date.getTime()) ? null : { date, normalized };
}

/** Inclusive calendar-day bounds for sessionDate lookups (DB DATE values are midnight UTC). */
function sessionDateQueryBounds(yyyyMmDd: string): { gte: Date; lt: Date } {
  const gte = toDbDateOnly(yyyyMmDd);
  const lt = new Date(gte);
  lt.setUTCDate(lt.getUTCDate() + 1);
  return { gte, lt };
}


/** CSV rows may use batch_id / delivery_batch_code / batch_code aliases. */
function csvBatchHints(row: Record<string, unknown>): { batchIdQuery: bigint | null; deliveryBatchCode: string | null } {
  const idRaw = row.batch_id ?? row.batchId ?? row.BatchId;
  const idStr = idRaw !== undefined && idRaw !== null ? String(idRaw).trim() : "";
  const batchIdQuery = /^\d+$/.test(idStr) ? BigInt(idStr) : null;
  const codeRaw = row.delivery_batch_code ?? row.batch_code ?? row.deliveryBatchCode ?? row.batchCode;
  const deliveryBatchCode = typeof codeRaw === "string" && codeRaw.trim() ? codeRaw.trim() : null;
  return { batchIdQuery, deliveryBatchCode };
}

function csvCohortIdRaw(row: Record<string, unknown>): string {
  const c = row.cohort_id ?? row.cohortId;
  return c !== undefined && c !== null ? String(c).trim() : "";
}

function csvCohortCodeRaw(row: Record<string, unknown>): string {
  const c = row.cohort_code ?? row.cohortCode;
  return c !== undefined && c !== null ? String(c).trim() : "";
}

const ATTENDANCE_IMPORT_HEADERS = [
  "external_beneficiary_id",
  "trainee_unique_id",
  "trainee_name",
  "roster_role",
  "session_date",
  "status",
  "cohort_code",
  "delivery_batch_code",
] as const;

function attendanceImportHeadersAreExact(headers: string[]): boolean {
  return (
    headers.length === ATTENDANCE_IMPORT_HEADERS.length &&
    ATTENDANCE_IMPORT_HEADERS.every((header, idx) => headers[idx] === header)
  );
}


type AttendanceDayUpsertInput = {
  projectId: bigint;
  trainingProviderId: bigint;
  trainingId: bigint;
  cohortId: bigint | null;
  batchId: bigint;
  traineeId: bigint;
  sessionDate: Date;
  status: string;
  source: string | null;
};

type AttendanceDb = Pick<typeof prisma, "traineeAttendanceDay">;

type CsvBreakdownLite = {
  cohortId: bigint | null;
  batchId: bigint | null;
  breakStartDate: Date;
  breakEndDate: Date;
};

/** Last entry wins when the same trainee appears more than once in one submission. */
function dedupeAttendanceEntries<T extends { traineeId: string }>(entries: T[]): T[] {
  const byTrainee = new Map<string, T>();
  for (const entry of entries) byTrainee.set(entry.traineeId, entry);
  return [...byTrainee.values()];
}

function dedupeStagedAttendanceRows<T extends { traineeId: bigint; batchId: bigint; sessionDate: Date }>(rows: T[]): T[] {
  const byKey = new Map<string, T>();
  for (const row of rows) {
    byKey.set(`${row.traineeId}:${row.batchId}:${sessionDateKey(row.sessionDate)}`, row);
  }
  return [...byKey.values()];
}

/** Upsert with P2002 fallback for concurrent duplicate submissions on the same trainee/day/batch. */
async function upsertTraineeAttendanceDay(db: AttendanceDb, input: AttendanceDayUpsertInput) {
  const where = {
    traineeId_batchId_sessionDate: {
      traineeId: input.traineeId,
      batchId: input.batchId,
      sessionDate: input.sessionDate,
    },
  };
  const create = {
    projectId: input.projectId,
    trainingProviderId: input.trainingProviderId,
    trainingId: input.trainingId,
    cohortId: input.cohortId,
    batchId: input.batchId,
    traineeId: input.traineeId,
    sessionDate: input.sessionDate,
    status: input.status,
    source: input.source,
  };
  const update = { status: input.status, source: input.source };
  try {
    return await db.traineeAttendanceDay.upsert({ where, create, update });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
      return await db.traineeAttendanceDay.update({ where, data: update });
    }
    throw e;
  }
}

function effectiveStartDate(startDate: Date, timelineAnchorDate?: Date | null): Date {
  return timelineAnchorDate ?? startDate;
}

function buildName(firstName: string, fatherName: string | null, grandfatherName: string | null) {
  return [firstName, fatherName ?? "", grandfatherName ?? ""].join(" ").replace(/\s+/g, " ").trim();
}

// scope helpers moved to services/scopePolicy.ts

async function writeSubmissionEvent(args: {
  projectId: bigint;
  trainingProviderId?: bigint | null;
  trainingId?: bigint | null;
  cohortId?: bigint | null;
  batchId?: bigint | null;
  action: string;
  sourceType?: string | null;
  sourceRef?: string | null;
  payloadRaw?: string | null;
  actorUserId?: bigint | null;
  meta?: Record<string, unknown>;
}) {
  await writeAuditEvent({
    projectId: args.projectId,
    trainingProviderId: args.trainingProviderId ?? null,
    trainingId: args.trainingId ?? null,
    cohortId: args.cohortId ?? null,
    batchId: args.batchId ?? null,
    module: "attendance",
    action: args.action,
    sourceType: args.sourceType ?? null,
    sourceRef: args.sourceRef ?? null,
    payloadRaw: args.payloadRaw ?? null,
    actorUserId: args.actorUserId ?? null,
    meta: (args.meta ?? undefined) as Prisma.InputJsonValue | undefined,
  });
}

function traineeEligibleForSessionDate(args: {
  range: TrainingDateRange;
  holidayDates: Date[];
  sessionDate: Date;
  breakdowns: AttendanceBreakdownRow[];
  deliveryBatchId: bigint;
  anchorStart: Date;
  exemptDays: number;
  trainee: { cohortId: bigint | null; attendanceEligibleFrom: Date | null };
}): boolean {
  const datesThrough = filterScheduledDatesExcludingExemptPeriod(
    scheduledSessionDates(args.range, args.holidayDates, args.sessionDate),
    args.anchorStart,
    args.exemptDays,
  );
  const excluded = traineeBreakdownExcludedKeysForDeliveryBatch(
    args.breakdowns,
    args.trainee.cohortId,
    args.deliveryBatchId,
  );
  const keys = eligibleSessionKeysForTrainee({
    sessionDatesOrdered: datesThrough,
    attendanceEligibleFrom: args.trainee.attendanceEligibleFrom,
    excludedSessionKeys: excluded,
  });
  return keys.includes(sessionDateKey(args.sessionDate));
}

function explainScheduleState(
  training: TrainingDateRange,
  holidayDates: Date[],
  sessionDate: Date,
  now: Date,
  anchorStart: Date,
  exemptDays: number,
): "scheduled" | "future_date" | "outside_training_range" | "weekday_not_enabled" | "holiday" | "exempt_period" {
  if (isSessionDateExempt(sessionDate, anchorStart, exemptDays)) return "exempt_period";
  const s = new Date(sessionDate.getFullYear(), sessionDate.getMonth(), sessionDate.getDate());
  const start = new Date(training.startDate.getFullYear(), training.startDate.getMonth(), training.startDate.getDate());
  const end = new Date(training.endDate.getFullYear(), training.endDate.getMonth(), training.endDate.getDate());
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  if (s.getTime() > today.getTime()) return "future_date";
  if (s.getTime() < start.getTime() || s.getTime() > end.getTime()) return "outside_training_range";
  const weekdays = new Set(parseSessionWeekdays(training.sessionWeekdays));
  if (!weekdays.has(isoWeekdayMonToSun(s))) return "weekday_not_enabled";
  const holidaySet = new Set(holidayDates.map((d) => sessionDateKey(d)));
  if (holidaySet.has(sessionDateKey(s))) return "holiday";
  return "scheduled";
}

async function resolveAttendanceDeliveryBatch(args: {
  projectId: bigint;
  trainingProviderId: bigint;
  trainingId: bigint;
  cohortIdQuery: bigint | null;
  batchIdQuery: bigint | null;
  deliveryBatchCode: string | null;
}): Promise<{ cohortId: bigint; batchId: bigint }> {
  let cohortIdForResolve = args.cohortIdQuery;
  if (args.batchIdQuery != null && cohortIdForResolve == null) {
    const batchRow = await prisma.trainingBatch.findFirst({
      where: {
        id: args.batchIdQuery,
        projectId: args.projectId,
        trainingId: args.trainingId,
        trainingProviderId: args.trainingProviderId,
      },
      select: { cohortId: true },
    });
    if (!batchRow) {
      throw Object.assign(new Error("Delivery batch not found for this training."), { status: 404 });
    }
    cohortIdForResolve = batchRow.cohortId;
  }
  const resolvedScope = await resolveTrainingScope({
    prisma,
    projectId: args.projectId,
    trainingProviderId: args.trainingProviderId,
    trainingId: args.trainingId,
    cohortId: cohortIdForResolve,
  });
  const batchId = await resolveTraineeDeliveryBatchId({
    prisma,
    cohortId: resolvedScope.effectiveCohortId,
    explicitBatchId: args.batchIdQuery,
    deliveryBatchCode: args.deliveryBatchCode ?? undefined,
  });
  return { cohortId: resolvedScope.effectiveCohortId, batchId };
}

async function resolveAndAssertAttendanceDeliveryBatch(
  scope: Awaited<ReturnType<typeof resolveScope>>,
  args: Parameters<typeof resolveAttendanceDeliveryBatch>[0],
) {
  const r = await resolveAttendanceDeliveryBatch(args);
  assertDeliveryScope(scope, { trainingId: args.trainingId, cohortId: r.cohortId, batchId: r.batchId });
  return r;
}

async function getBreakdownBlockForDate(args: {
  projectId: bigint;
  trainingId: bigint;
  cohortId: bigint | null;
  batchId: bigint | null;
  sessionDate: Date;
}) {
  const orCriteria: Array<Record<string, unknown>> = [{ cohortId: null, batchId: null }];
  if (args.cohortId != null) orCriteria.push({ cohortId: args.cohortId, batchId: null });
  if (args.batchId != null) orCriteria.push({ batchId: args.batchId });

  const hit = await prisma.trainingBreakdown.findFirst({
    where: {
      projectId: args.projectId,
      trainingId: args.trainingId,
      status: "approved",
      breakStartDate: { lte: args.sessionDate },
      breakEndDate: { gte: args.sessionDate },
      OR: orCriteria,
    },
    select: { id: true, cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true, reason: true },
  });
  if (!hit) return null;
  return {
    breakdownId: asId(hit.id),
    scope: hit.batchId ? "batch" : hit.cohortId ? "cohort" : "training",
    breakStartDate: hit.breakStartDate.toISOString().slice(0, 10),
    breakEndDate: hit.breakEndDate.toISOString().slice(0, 10),
    reason: hit.reason,
  } as const;
}

function findPrefetchedBreakdownBlock(args: {
  breakdowns: CsvBreakdownLite[];
  cohortId: bigint | null;
  batchId: bigint | null;
  sessionDate: Date;
}) {
  // Mirror getBreakdownBlockForDate OR criteria:
  // training-wide (null/null), cohort-wide (cohort + null batch), batch-specific (batch id).
  const hit = args.breakdowns.find((b) => {
    if (b.breakStartDate > args.sessionDate || b.breakEndDate < args.sessionDate) return false;
    if (b.batchId == null && b.cohortId == null) return true;
    if (args.cohortId != null && b.batchId == null && b.cohortId === args.cohortId) return true;
    if (args.batchId != null && b.batchId != null && b.batchId === args.batchId) return true;
    return false;
  });
  if (!hit) return null;
  return {
    scope: hit.batchId ? "batch" : hit.cohortId ? "cohort" : "training",
    breakStartDate: hit.breakStartDate.toISOString().slice(0, 10),
    breakEndDate: hit.breakEndDate.toISOString().slice(0, 10),
  } as const;
}

/** ——— Attendance policy (global exempt period; readable by TPs) ——— */

router.get(
  "/projects/:projectId/attendance-policy",
  requirePermission("view:attendance", { 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 attendanceExemptDaysFromScopeStart = await loadAttendanceExemptDaysFromStart(prisma);
    res.json({ attendanceExemptDaysFromScopeStart });
  },
);

/** ——— Project holidays ——— */

router.get(
  "/projects/:projectId/attendance/holidays",
  requirePermission("view:attendance", { 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 rows = await prisma.projectHoliday.findMany({
      where: { projectId },
      orderBy: { holidayDate: "asc" },
    });
    res.json({
      items: rows.map((h) => ({
        id: asId(h.id),
        holidayDate: h.holidayDate.toISOString().slice(0, 10),
        label: h.label,
      })),
    });
  },
);

router.post(
  "/projects/:projectId/attendance/holidays",
  requirePermission("manage:trainings", { 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({ holidayDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), label: z.string().optional() }).safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid body", details: parsed.error.flatten() });
    const d = new Date(parsed.data.holidayDate + "T12:00:00");
    const row = await prisma.projectHoliday.upsert({
      where: { projectId_holidayDate: { projectId, holidayDate: d } },
      create: { projectId, holidayDate: d, label: parsed.data.label?.trim() || null },
      update: { label: parsed.data.label?.trim() || null },
    });
    res.json({ item: { id: asId(row.id), holidayDate: row.holidayDate.toISOString().slice(0, 10), label: row.label } });
  },
);

router.delete(
  "/projects/:projectId/attendance/holidays/:holidayId",
  requirePermission("manage:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const holidayId = BigInt(req.params.holidayId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const ex = await prisma.projectHoliday.findFirst({ where: { id: holidayId, projectId } });
    if (!ex) return void res.status(404).json({ error: "Not found." });
    await prisma.projectHoliday.delete({ where: { id: holidayId } });
    res.json({ ok: true });
  },
);

router.get(
  "/projects/:projectId/attendance/summary",
  requirePermission("view:attendance", { 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 scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const agg = await computeAttendancePresentPossible(projectId);
    const coverageByTp = await computeAttendanceSubmissionCoverageByTp(projectId);
    const items: Array<{ tpId: string; present: number; possible: number; ratePct: number }> = [];
    const coverageItems: Array<{ tpId: string; sessionDaysSubmitted: number; sessionDaysDue: number; coveragePct: number }> = [];
    for (const [tpId, v] of agg.byTp) {
      if (scope.providerId && scope.providerId.toString() !== tpId) continue;
      const ratePct = v.possible > 0 ? Math.round((v.present / v.possible) * 10000) / 100 : 0;
      items.push({ tpId, present: v.present, possible: v.possible, ratePct });
    }
    let projectSessionDaysSubmitted = 0;
    let projectSessionDaysDue = 0;
    for (const [tpId, v] of coverageByTp) {
      if (scope.providerId && scope.providerId.toString() !== tpId) continue;
      coverageItems.push({
        tpId,
        sessionDaysSubmitted: v.sessionDaysSubmitted,
        sessionDaysDue: v.sessionDaysDue,
        coveragePct: v.coveragePct,
      });
      projectSessionDaysSubmitted += v.sessionDaysSubmitted;
      projectSessionDaysDue += v.sessionDaysDue;
    }
    const totalRate = agg.possible > 0 ? Math.round((agg.present / agg.possible) * 10000) / 100 : 0;
    const projectCoveragePct =
      projectSessionDaysDue > 0 ? Math.round((projectSessionDaysSubmitted / projectSessionDaysDue) * 10000) / 100 : 0;
    res.json({
      project: { present: agg.present, possible: agg.possible, ratePct: totalRate },
      items,
      coverageProject: {
        sessionDaysSubmitted: projectSessionDaysSubmitted,
        sessionDaysDue: projectSessionDaysDue,
        coveragePct: projectCoveragePct,
      },
      coverageItems,
      policy:
        "Denominator = eligible scheduled sessions per active cohort member (minus holidays/breakdowns and days before attendance eligibility start). Reserve roster excluded until promoted. Numerator = present + excused within eligibility.",
      coveragePolicy:
        "Daily submission coverage = fully submitted session days ÷ eligible session days due through today (not future training dates). A day counts when every eligible active/reserve trainee in that delivery batch has an attendance row.",
    });
  },
);

router.get(
  "/projects/:projectId/attendance/submission-coverage-breakdown",
  requirePermission("view:attendance", { 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 scope = await resolveScope(projectId, req.auth!.userId);
    try {
      assertTpAssigned(scope);
    } catch (e) {
      return void res.status((e as any).status ?? 403).json({ error: (e as Error).message });
    }
    const requestedTpId =
      typeof req.query.trainingProviderId === "string" && /^\d+$/.test(req.query.trainingProviderId)
        ? BigInt(req.query.trainingProviderId)
        : null;
    const effectiveTpId = scope.providerId ?? requestedTpId;
    const items = await computeAttendanceSubmissionCoverageBreakdown(projectId, {
      trainingProviderId: effectiveTpId ?? undefined,
    });
    res.json({
      items,
      policy:
        "Each row is one delivery batch. Submission coverage = fully submitted session days ÷ eligible session days due through today.",
    });
  },
);

/** Daily recorded attendance (one point per session date that has rows in trainee_attendance_days). */
router.get(
  "/projects/:projectId/attendance/daily-series",
  requirePermission("view:attendance", { 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 scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const limitRaw = req.query.limit ? Number(String(req.query.limit)) : 42;
    const limit = Number.isFinite(limitRaw) ? Math.min(365, Math.max(7, Math.floor(limitRaw))) : 42;
    const requestedTpId =
      typeof req.query.trainingProviderId === "string" && /^\d+$/.test(req.query.trainingProviderId)
        ? BigInt(req.query.trainingProviderId)
        : null;
    const effectiveTpId = scope.providerId ?? requestedTpId;

    const items = await fetchAttendanceDailySeries(
      projectId,
      limit,
      effectiveTpId ?? undefined,
    );
    res.json({ items });
  },
);

/** ——— Per-training session calendar preview ——— */

router.get(
  "/projects/:projectId/trainings/:trainingId/attendance/calendar",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });
    const holidays = await prisma.projectHoliday.findMany({ where: { projectId }, select: { holidayDate: true } });
    const t: TrainingDateRange = {
      startDate: effectiveStartDate(tr.startDate, tr.timelineAnchorDate),
      endDate: tr.endDate,
      sessionWeekdays: tr.sessionWeekdays,
    };
    const dates = scheduledSessionDates(t, holidays.map((h) => h.holidayDate), new Date());
    res.json({
      sessionWeekdays: parseSessionWeekdays(tr.sessionWeekdays),
      sessionDates: dates.map((d) => sessionDateKey(d)),
    });
  },
);

/** Dates on which this training (and optional cohort) already has ≥1 attendance row. */
router.get(
  "/projects/:projectId/trainings/:trainingId/attendance/submitted-dates",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortQ = typeof req.query.cohortId === "string" && /^\d+$/.test(req.query.cohortId) ? BigInt(req.query.cohortId) : null;
    const batchIdQ =
      typeof req.query.batchId === "string" && /^\d+$/.test(req.query.batchId) ? BigInt(req.query.batchId) : null;
    const deliveryBatchCode =
      typeof req.query.deliveryBatchCode === "string" && req.query.deliveryBatchCode.trim()
        ? req.query.deliveryBatchCode.trim()
        : null;
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { trainingProviderId: true },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });
    let effectiveBatchId: bigint;
    try {
      const r = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortIdQuery: cohortQ,
        batchIdQuery: batchIdQ,
        deliveryBatchCode,
      });
      effectiveBatchId = r.batchId;
    } catch (e) {
      return void res.status((e as any).status ?? 400).json({ error: (e as Error).message });
    }
    const grouped = await prisma.traineeAttendanceDay.groupBy({
      by: ["sessionDate"],
      where: {
        projectId,
        trainingId,
        batchId: effectiveBatchId,
      },
    });
    const dates = grouped.map((g) => sessionDateKey(g.sessionDate)).sort();
    res.json({ dates });
  },
);

const ATTENDANCE_EXPORT_HEADERS = [
  "session_date",
  "trainee_unique_id",
  "external_beneficiary_id",
  "trainee_name",
  "roster_role",
  "status",
  "cohort_code",
  "delivery_batch_code",
] as const;

function attendanceExportCsvEscape(value: string): string {
  if (/[",\n\r]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
  return value;
}

function attendanceExportDateCell(yyyyMmDd: string): string {
  return `="${yyyyMmDd}"`;
}

function parseAttendanceExportDates(raw: string | string[] | undefined): string[] {
  const parts = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [];
  const out: string[] = [];
  for (const part of parts) {
    const d = part.trim();
    if (!d) continue;
    if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) continue;
    if (!out.includes(d)) out.push(d);
  }
  return out.sort();
}

/** Export submitted attendance rows as CSV (for reconciliation with physical records). */
router.get(
  "/projects/:projectId/trainings/:trainingId/attendance/export",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortQ = typeof req.query.cohortId === "string" && /^\d+$/.test(req.query.cohortId) ? BigInt(req.query.cohortId) : null;
    const batchIdQ =
      typeof req.query.batchId === "string" && /^\d+$/.test(req.query.batchId) ? BigInt(req.query.batchId) : null;
    const deliveryBatchCode =
      typeof req.query.deliveryBatchCode === "string" && req.query.deliveryBatchCode.trim()
        ? req.query.deliveryBatchCode.trim()
        : null;
    const allSubmitted = String(req.query.allSubmitted ?? "").toLowerCase() === "true";
    const requestedDates = parseAttendanceExportDates(
      typeof req.query.dates === "string" ? req.query.dates : undefined,
    );

    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try {
      assertTpAssigned(scope);
    } catch (e) {
      return void res.status((e as any).status ?? 403).json({ error: (e as Error).message });
    }

    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, trainingProviderId: true, title: true },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });

    let effectiveCohortId: bigint;
    let effectiveBatchId: bigint;
    try {
      const resolved = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortIdQuery: cohortQ,
        batchIdQuery: batchIdQ,
        deliveryBatchCode,
      });
      effectiveCohortId = resolved.cohortId;
      effectiveBatchId = resolved.batchId;
    } catch (e) {
      return void res.status((e as any).status ?? 400).json({ error: (e as Error).message });
    }

    const [cohortRow, batchRow] = await Promise.all([
      prisma.trainingCohort.findFirst({
        where: { id: effectiveCohortId, trainingId, projectId },
        select: { code: true },
      }),
      prisma.trainingBatch.findFirst({
        where: { id: effectiveBatchId, trainingId, projectId },
        select: { code: true },
      }),
    ]);
    if (!cohortRow || !batchRow) return void res.status(404).json({ error: "Cohort or delivery batch not found." });

    let exportDates = requestedDates;
    if (allSubmitted) {
      const grouped = await prisma.traineeAttendanceDay.groupBy({
        by: ["sessionDate"],
        where: { projectId, trainingId, batchId: effectiveBatchId },
      });
      exportDates = grouped.map((g) => sessionDateKey(g.sessionDate)).sort();
    }

    if (!exportDates.length) {
      return void res.status(400).json({ error: "No submitted session dates to export for this scope." });
    }
    if (exportDates.length > 400) {
      return void res.status(400).json({ error: "Too many dates in one export (max 400). Export in smaller batches." });
    }

    const dateBounds = exportDates.map((d) => toDbDateOnly(d));
    const minDate = dateBounds.reduce((a, b) => (a.getTime() <= b.getTime() ? a : b));
    const maxDate = dateBounds.reduce((a, b) => (a.getTime() >= b.getTime() ? a : b));
    const maxExclusive = new Date(maxDate.getTime() + 24 * 60 * 60 * 1000);
    const exportDateSet = new Set(exportDates);

    const rows = await prisma.traineeAttendanceDay.findMany({
      where: {
        projectId,
        trainingId,
        batchId: effectiveBatchId,
        sessionDate: { gte: minDate, lt: maxExclusive },
      },
      select: {
        sessionDate: true,
        status: true,
        trainee: {
          select: {
            traineeUniqueId: true,
            externalBeneficiaryId: true,
            firstName: true,
            fatherName: true,
            grandfatherName: true,
            rosterRole: true,
          },
        },
      },
      orderBy: [{ sessionDate: "asc" }, { trainee: { traineeUniqueId: "asc" } }],
    });

    const cohortCode = cohortRow.code;
    const batchCode = batchRow.code;
    const csvLines = [ATTENDANCE_EXPORT_HEADERS.join(",")];
    let rowCount = 0;
    for (const row of rows) {
      const sessionDate = sessionDateKey(row.sessionDate);
      if (!exportDateSet.has(sessionDate)) continue;
      const t = row.trainee;
      csvLines.push(
        [
          attendanceExportDateCell(sessionDate),
          attendanceExportCsvEscape(t.traineeUniqueId),
          attendanceExportCsvEscape(t.externalBeneficiaryId ?? ""),
          attendanceExportCsvEscape(buildName(t.firstName, t.fatherName ?? null, t.grandfatherName ?? null)),
          attendanceExportCsvEscape(String(t.rosterRole ?? "active")),
          attendanceExportCsvEscape(row.status),
          attendanceExportCsvEscape(cohortCode),
          attendanceExportCsvEscape(batchCode),
        ].join(","),
      );
      rowCount += 1;
    }

    if (rowCount === 0) {
      return void res.status(400).json({ error: "No attendance rows found for the selected session dates." });
    }

    const slug = String(tr.title)
      .trim()
      .replace(/[^\w\-]+/g, "-")
      .replace(/-+/g, "-")
      .slice(0, 40);
    const fileName = `attendance-export-${slug || trainingId}-${batchCode}-${exportDates.length}days.csv`;
    res.setHeader("Content-Type", "text/csv; charset=utf-8");
    res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
    res.send(`${csvLines.join("\n")}\n`);
  },
);

router.get(
  "/projects/:projectId/trainings/:trainingId/attendance/summary",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortId =
      typeof req.query.cohortId === "string" && /^\d+$/.test(req.query.cohortId) ? BigInt(req.query.cohortId) : null;
    const batchIdQ =
      typeof req.query.batchId === "string" && /^\d+$/.test(req.query.batchId) ? BigInt(req.query.batchId) : null;
    const deliveryBatchCode =
      typeof req.query.deliveryBatchCode === "string" && req.query.deliveryBatchCode.trim()
        ? req.query.deliveryBatchCode.trim()
        : null;
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const trFull = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, trainingProviderId: true },
    });
    if (!trFull) return void res.status(404).json({ error: "Training not found." });
    let cohort: { id: bigint } | null = null;
    let effectiveBatchId: bigint;
    try {
      const resolved = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: trFull.trainingProviderId,
        trainingId,
        cohortIdQuery: cohortId,
        batchIdQuery: batchIdQ,
        deliveryBatchCode,
      });
      effectiveBatchId = resolved.batchId;
      cohort = await prisma.trainingCohort.findFirst({
        where: { id: resolved.cohortId, trainingId, projectId },
        select: { id: true },
      });
      if (!cohort) return void res.status(404).json({ error: "Cohort not found." });
    } catch (e) {
      return void res.status((e as any).status ?? 400).json({ error: (e as Error).message });
    }
    const { present, possible } = await computeAttendancePresentPossibleForTrainingScope(
      projectId,
      trainingId,
      cohort.id,
      effectiveBatchId,
    );
    const ratePct = possible > 0 ? Math.round((present / possible) * 10000) / 100 : 0;
    res.json({
      trainingId: asId(trainingId),
      cohortId: asId(cohort.id),
      batchId: asId(effectiveBatchId),
      present,
      possible,
      ratePct,
    });
  }
);

/** Per-trainee attendance rates for one provider (ICOS export): attended ÷ eligible scheduled sessions. */
router.get(
  "/projects/:projectId/providers/:providerId/attendance-export",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try {
      assertTpAssigned(scope);
      enforceProviderScope(scope, providerId);
    } catch (e) {
      return void res.status((e as { status?: number }).status ?? 403).json({ error: (e as Error).message });
    }

    const provider = await prisma.trainingProvider.findFirst({
      where: { id: providerId, projectId },
      select: { tpCode: true, name: true },
    });
    if (!provider) return void res.status(404).json({ error: "Provider not found." });

    const rows = (await computeTraineeAttendanceRatesForProvider(projectId, providerId)).filter((r) =>
      isDeliveryScopeAllowed(scope, { trainingId: r.trainingId, cohortId: r.cohortId, batchId: r.batchId }),
    );
    if (rows.length === 0) {
      return void res.status(400).json({ error: "No trainees on the tracked roster for this provider." });
    }

    const headers = [
      "provider_code",
      "provider_name",
      "training",
      "cohort",
      "delivery_batch",
      "trainee_unique_id",
      "external_beneficiary_id",
      "trainee_name",
      "sex",
      "roster_role",
      "attendance_eligible_from",
      "sessions_attended",
      "sessions_possible",
      "attendance_rate_pct",
    ];
    const csvLines = [headers.join(",")];
    for (const r of rows) {
      csvLines.push(
        [
          attendanceExportCsvEscape(provider.tpCode),
          attendanceExportCsvEscape(provider.name),
          attendanceExportCsvEscape(r.trainingTitle),
          attendanceExportCsvEscape(r.cohortCode ? `${r.cohortCode} — ${r.cohortName ?? ""}` : ""),
          attendanceExportCsvEscape(r.batchCode ? `${r.batchCode} — ${r.batchName ?? ""}` : ""),
          attendanceExportCsvEscape(r.traineeUniqueId),
          attendanceExportCsvEscape(r.externalBeneficiaryId ?? ""),
          attendanceExportCsvEscape(buildName(r.firstName, r.fatherName, r.grandfatherName)),
          attendanceExportCsvEscape(r.sex),
          attendanceExportCsvEscape(r.rosterRole),
          r.attendanceEligibleFrom ? attendanceExportDateCell(sessionDateKey(r.attendanceEligibleFrom)) : "",
          String(r.present),
          String(r.possible),
          r.ratePct == null ? "" : String(r.ratePct),
        ].join(","),
      );
    }

    const slug = provider.tpCode.replace(/[^\w\-]+/g, "-").replace(/-+/g, "-").slice(0, 40) || providerId.toString();
    const fileName = `attendance-rates-${slug}-${sessionDateKey(new Date())}.csv`;
    res.setHeader("Content-Type", "text/csv; charset=utf-8");
    res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
    res.send(`${csvLines.join("\n")}\n`);
  },
);

/** ——— Daily attendance for one session date ——— */

router.get(
  "/projects/:projectId/trainings/:trainingId/attendance/roster",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortId =
      typeof req.query.cohortId === "string" && /^\d+$/.test(req.query.cohortId) ? BigInt(req.query.cohortId) : null;
    const batchIdQ =
      typeof req.query.batchId === "string" && /^\d+$/.test(req.query.batchId) ? BigInt(req.query.batchId) : null;
    const deliveryBatchCode =
      typeof req.query.deliveryBatchCode === "string" && req.query.deliveryBatchCode.trim()
        ? req.query.deliveryBatchCode.trim()
        : null;
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }

    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, trainingProviderId: true },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });

    let effectiveCohortId: bigint;
    let effectiveBatchId: bigint;
    try {
      const resolved = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortIdQuery: cohortId,
        batchIdQuery: batchIdQ,
        deliveryBatchCode,
      });
      effectiveCohortId = resolved.cohortId;
      effectiveBatchId = resolved.batchId;
    } catch (e) {
      return void res.status((e as any).status ?? 400).json({ error: (e as Error).message });
    }

    const traineeRowsRaw = await prisma.trainee.findMany({
      where: {
        projectId,
        trainingId,
        cohortId: effectiveCohortId,
        batchId: effectiveBatchId,
        ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}),
      },
      select: {
        id: true,
        traineeUniqueId: true,
        externalBeneficiaryId: true,
        firstName: true,
        fatherName: true,
        grandfatherName: true,
        rosterRole: true,
      },
      orderBy: { id: "asc" },
    });
    const traineeRows = traineeRowsRaw.filter((x) => rosterRoleReceivesAttendanceCapture(x.rosterRole));
    res.json({
      cohortId: asId(effectiveCohortId),
      batchId: asId(effectiveBatchId),
      trainees: traineeRows.map((x) => ({
        traineeId: asId(x.id),
        traineeUniqueId: x.traineeUniqueId,
        externalBeneficiaryId: x.externalBeneficiaryId,
        traineeName: buildName(x.firstName, x.fatherName ?? null, x.grandfatherName ?? null),
        firstName: x.firstName,
        rosterRole: x.rosterRole,
      })),
    });
  },
);

router.get(
  "/projects/:projectId/trainings/:trainingId/attendance/day",
  requirePermission("view:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortId =
      typeof req.query.cohortId === "string" && /^\d+$/.test(req.query.cohortId) ? BigInt(req.query.cohortId) : null;
    const batchIdQ =
      typeof req.query.batchId === "string" && /^\d+$/.test(req.query.batchId) ? BigInt(req.query.batchId) : null;
    const deliveryBatchCode =
      typeof req.query.deliveryBatchCode === "string" && req.query.deliveryBatchCode.trim()
        ? req.query.deliveryBatchCode.trim()
        : null;
    const sessionDateStr = typeof req.query.sessionDate === "string" ? req.query.sessionDate : "";
    if (!/^\d{4}-\d{2}-\d{2}$/.test(sessionDateStr)) return void res.status(400).json({ error: "sessionDate=YYYY-MM-DD required" });
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: {
        id: true,
        trainingProviderId: true,
        sessionWeekdays: true,
      },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });
    let effectiveCohortId: bigint;
    let effectiveBatchId: bigint;
    try {
      const resolved = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortIdQuery: cohortId,
        batchIdQuery: batchIdQ,
        deliveryBatchCode,
      });
      effectiveCohortId = resolved.cohortId;
      effectiveBatchId = resolved.batchId;
    } catch (e) {
      return void res.status((e as any).status ?? 400).json({ error: (e as Error).message });
    }
    const traineeRowsRaw = await prisma.trainee.findMany({
      where: {
        projectId,
        trainingId,
        cohortId: effectiveCohortId,
        batchId: effectiveBatchId,
        ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}),
      },
      select: {
        id: true,
        traineeUniqueId: true,
        externalBeneficiaryId: true,
        firstName: true,
        fatherName: true,
        grandfatherName: true,
        cohortId: true,
        batchId: true,
        rosterRole: true,
        attendanceEligibleFrom: true,
      },
      orderBy: { id: "asc" },
    });
    const traineeRows = traineeRowsRaw.filter((x) => rosterRoleReceivesAttendanceCapture(x.rosterRole));
    const sessionDate = toDbDateOnly(sessionDateStr);
    const sessionBounds = sessionDateQueryBounds(sessionDateStr);
    const holidays = await prisma.projectHoliday.findMany({ where: { projectId }, select: { holidayDate: true } });
    const batchRow = await prisma.trainingBatch.findFirst({
      where: { id: effectiveBatchId, trainingId, projectId },
      select: { startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true },
    });
    if (!batchRow) return void res.status(404).json({ error: "Delivery batch not found." });
    const anchorStart = effectiveStartDate(batchRow.startDate, batchRow.timelineAnchorDate);
    const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);
    const sessionRange: TrainingDateRange = {
      startDate: anchorStart,
      endDate: batchRow.endDate,
      sessionWeekdays: batchRow.sessionWeekdays ?? tr.sessionWeekdays,
    };
    const holidayDates = holidays.map((h) => h.holidayDate);
    const scheduleState = explainScheduleState(sessionRange, holidayDates, sessionDate, new Date(), anchorStart, exemptDays);
    const allowed = scheduleState === "scheduled";
    const breakdowns = await prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, status: "approved" },
      select: { cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
    });
    const rows = await prisma.traineeAttendanceDay.findMany({
      where: {
        trainingId,
        batchId: effectiveBatchId,
        sessionDate: { gte: sessionBounds.gte, lt: sessionBounds.lt },
      },
    });
    const breakdownBlock = await getBreakdownBlockForDate({
      projectId,
      trainingId,
      cohortId: effectiveCohortId,
      batchId: effectiveBatchId,
      sessionDate,
    });
    const byTrainee = new Map(rows.map((r) => [r.traineeId.toString(), r.status]));
    res.json({
      sessionDate: sessionDateStr,
      isScheduledSession: allowed,
      scheduleState,
      blockedByBreakdown: Boolean(breakdownBlock),
      breakdownBlock,
      ...exemptPeriodMeta(anchorStart, exemptDays),
      // Return all scoped trainees so manual roster never appears empty just because the
      // selected date is out-of-range / before eligibility / etc. The PUT endpoint still
      // enforces eligibility and will block invalid submissions.
      trainees: traineeRows.map((x) => {
        const eligible = traineeEligibleForSessionDate({
          range: sessionRange,
          holidayDates,
          sessionDate,
          breakdowns,
          deliveryBatchId: effectiveBatchId,
          anchorStart,
          exemptDays,
          trainee: x,
        });
        return {
          traineeId: asId(x.id),
          traineeUniqueId: x.traineeUniqueId,
          externalBeneficiaryId: x.externalBeneficiaryId,
          traineeName: buildName(x.firstName, x.fatherName ?? null, x.grandfatherName ?? null),
          firstName: x.firstName,
          rosterRole: x.rosterRole,
          eligible,
          status: (byTrainee.get(asId(x.id)) as string | undefined) ?? null,
        };
      }),
    });
  },
);

router.put(
  "/projects/:projectId/trainings/:trainingId/attendance/day",
  requirePermission("submit:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const parsed = z
      .object({
        cohortId: z.string().regex(/^\d+$/).optional(),
        batchId: z.string().regex(/^\d+$/).optional(),
        deliveryBatchCode: z.string().min(1).max(64).optional(),
        sessionDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
        source: z.enum(["manual", "csv_daily"]).optional(),
        entries: z.array(z.object({ traineeId: z.string(), status: z.enum(["present", "absent"]) })),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid body", details: parsed.error.flatten() });

    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      include: {
        trainees: {
          select: { id: true, cohortId: true, batchId: true, rosterRole: true, attendanceEligibleFrom: true },
        },
      },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });
    let effectiveCohortId: bigint;
    let effectiveBatchId: bigint;
    try {
      const r = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortIdQuery: parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null,
        batchIdQuery: parsed.data.batchId ? BigInt(parsed.data.batchId) : null,
        deliveryBatchCode: parsed.data.deliveryBatchCode ?? null,
      });
      effectiveCohortId = r.cohortId;
      effectiveBatchId = r.batchId;
    } catch (e) {
      return void res.status(400).json({ error: (e as Error).message });
    }

    const sessionDate = toDbDateOnly(parsed.data.sessionDate);
    const sessionBounds = sessionDateQueryBounds(parsed.data.sessionDate);
    const breakdownBlock = await getBreakdownBlockForDate({
      projectId,
      trainingId,
      cohortId: effectiveCohortId,
      batchId: effectiveBatchId,
      sessionDate,
    });
    if (breakdownBlock) {
      return void res.status(422).json({
        error: "Attendance submission blocked: this date is within an approved training/breakdown window.",
        breakdown: breakdownBlock,
      });
    }
    const holidays = await prisma.projectHoliday.findMany({ where: { projectId }, select: { holidayDate: true } });
    const holidayDates = holidays.map((h) => h.holidayDate);
    const batchRow = await prisma.trainingBatch.findFirst({
      where: { id: effectiveBatchId, trainingId, projectId },
      select: { startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true },
    });
    if (!batchRow) return void res.status(404).json({ error: "Delivery batch not found." });
    const anchorStart = effectiveStartDate(batchRow.startDate, batchRow.timelineAnchorDate);
    const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);
    if (isSessionDateExempt(sessionDate, anchorStart, exemptDays)) {
      const firstDay = firstAttendanceTrackingDay(anchorStart, exemptDays);
      return void res.status(422).json({
        error: `Attendance is not required during the no-attendance startup period (${anchorStart.toISOString().slice(0, 10)} through ${exemptPeriodMeta(anchorStart, exemptDays).exemptPeriodEnd ?? anchorStart.toISOString().slice(0, 10)}). First tracking day: ${firstDay.toISOString().slice(0, 10)}.`,
        scheduleState: "exempt_period",
        ...exemptPeriodMeta(anchorStart, exemptDays),
      });
    }
    const sessionRange: TrainingDateRange = {
      startDate: anchorStart,
      endDate: batchRow.endDate,
      sessionWeekdays: batchRow.sessionWeekdays ?? tr.sessionWeekdays,
    };
    if (!isScheduledSessionDate(sessionRange, holidayDates, sessionDate, new Date())) {
      return void res.status(400).json({
        error: "This date is not a scheduled training session (check weekday pattern, holidays, or delivery batch dates).",
      });
    }
    const breakdowns = await prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, status: "approved" },
      select: { cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
    });
    const existingForSession = await prisma.traineeAttendanceDay.count({
      where: {
        trainingId,
        batchId: effectiveBatchId,
        sessionDate: { gte: sessionBounds.gte, lt: sessionBounds.lt },
      },
    });
    if (existingForSession > 0) {
      return void res.status(409).json({
        error: "Attendance for this date is already recorded for this delivery batch. Duplicate submission is blocked.",
      });
    }

    const scopedTrainees = tr.trainees.filter(
      (x) =>
        rosterRoleReceivesAttendanceCapture(x.rosterRole) &&
        x.cohortId?.toString() === effectiveCohortId.toString() &&
        x.batchId?.toString() === effectiveBatchId.toString(),
    );
    const traineeById = new Map(scopedTrainees.map((x) => [x.id.toString(), x]));
    const source = parsed.data.source ?? "manual";
    let upserted = 0;
    for (const e of dedupeAttendanceEntries(parsed.data.entries)) {
      const row = traineeById.get(e.traineeId);
      if (!row || !row.batchId) continue;
      if (row.batchId !== effectiveBatchId) {
        return void res.status(422).json({ error: "Trainee batch does not match the selected delivery batch for this attendance session." });
      }
      if (
        !traineeEligibleForSessionDate({
          range: sessionRange,
          holidayDates,
          sessionDate,
          breakdowns,
          deliveryBatchId: effectiveBatchId,
          anchorStart,
          exemptDays,
          trainee: row,
        })
      ) {
        return void res.status(422).json({
          error:
            "One or more trainees are not eligible for this session date (check batch schedule, holidays, approved breakdown, or no-attendance startup period).",
        });
      }
      const traineeIdRow = BigInt(e.traineeId);
      await upsertTraineeAttendanceDay(prisma, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortId: row.cohortId,
        batchId: row.batchId,
        traineeId: traineeIdRow,
        sessionDate,
        status: e.status,
        source,
      });
      upserted++;
    }
    await writeSubmissionEvent({
      projectId,
      trainingProviderId: tr.trainingProviderId,
      trainingId,
      cohortId: effectiveCohortId,
      batchId: effectiveBatchId,
      action: "manual_day_submit",
      sourceType: source,
      sourceRef: parsed.data.sessionDate,
      payloadRaw: JSON.stringify(parsed.data),
      actorUserId: req.auth!.userId,
      meta: { upserted },
    });
    res.json({ ok: true, upserted });
  },
);

router.post(
  "/projects/:projectId/trainings/:trainingId/attendance/day/backfill-missing",
  requirePermission("submit:attendance"),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const parsed = z
      .object({
        cohortId: z.string().regex(/^\d+$/).optional(),
        batchId: z.string().regex(/^\d+$/).optional(),
        deliveryBatchCode: z.string().min(1).max(64).optional(),
        sessionDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
        dryRun: z.boolean().optional(),
        entries: z.array(z.object({ traineeId: z.string(), status: z.enum(["present", "absent"]) })),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid body", details: parsed.error.flatten() });

    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      include: {
        trainees: {
          select: { id: true, cohortId: true, batchId: true, rosterRole: true, attendanceEligibleFrom: true },
        },
      },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });
    let effectiveCohortId: bigint;
    let effectiveBatchId: bigint;
    try {
      const r = await resolveAndAssertAttendanceDeliveryBatch(scope, {
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortIdQuery: parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null,
        batchIdQuery: parsed.data.batchId ? BigInt(parsed.data.batchId) : null,
        deliveryBatchCode: parsed.data.deliveryBatchCode ?? null,
      });
      effectiveCohortId = r.cohortId;
      effectiveBatchId = r.batchId;
    } catch (e) {
      return void res.status(400).json({ error: (e as Error).message });
    }

    const sessionDate = toDbDateOnly(parsed.data.sessionDate);
    const sessionBounds = sessionDateQueryBounds(parsed.data.sessionDate);
    const breakdownBlock = await getBreakdownBlockForDate({
      projectId,
      trainingId,
      cohortId: effectiveCohortId,
      batchId: effectiveBatchId,
      sessionDate,
    });
    if (breakdownBlock) {
      return void res.status(422).json({
        error: "Attendance backfill blocked: this date is within an approved training/breakdown window.",
        breakdown: breakdownBlock,
      });
    }
    const holidays = await prisma.projectHoliday.findMany({ where: { projectId }, select: { holidayDate: true } });
    const holidayDates = holidays.map((h) => h.holidayDate);
    const batchRow = await prisma.trainingBatch.findFirst({
      where: { id: effectiveBatchId, trainingId, projectId },
      select: { startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true },
    });
    if (!batchRow) return void res.status(404).json({ error: "Delivery batch not found." });
    const anchorStart = effectiveStartDate(batchRow.startDate, batchRow.timelineAnchorDate);
    const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);
    if (isSessionDateExempt(sessionDate, anchorStart, exemptDays)) {
      const firstDay = firstAttendanceTrackingDay(anchorStart, exemptDays);
      return void res.status(422).json({
        error: `Attendance is not required during the no-attendance startup period (${anchorStart.toISOString().slice(0, 10)} through ${exemptPeriodMeta(anchorStart, exemptDays).exemptPeriodEnd ?? anchorStart.toISOString().slice(0, 10)}). First tracking day: ${firstDay.toISOString().slice(0, 10)}.`,
        scheduleState: "exempt_period",
        ...exemptPeriodMeta(anchorStart, exemptDays),
      });
    }
    const sessionRange: TrainingDateRange = {
      startDate: anchorStart,
      endDate: batchRow.endDate,
      sessionWeekdays: batchRow.sessionWeekdays ?? tr.sessionWeekdays,
    };
    if (!isScheduledSessionDate(sessionRange, holidayDates, sessionDate, new Date())) {
      return void res.status(400).json({
        error: "This date is not a scheduled training session (check weekday pattern, holidays, or delivery batch dates).",
      });
    }
    const existingForSession = await prisma.traineeAttendanceDay.count({
      where: {
        trainingId,
        batchId: effectiveBatchId,
        sessionDate: { gte: sessionBounds.gte, lt: sessionBounds.lt },
      },
    });
    if (existingForSession === 0) {
      return void res.status(409).json({
        error: "No submitted attendance found for this date and delivery batch. Use normal day submission instead.",
      });
    }
    const breakdowns = await prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, status: "approved" },
      select: { cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
    });

    const scopedTrainees = tr.trainees.filter(
      (x) =>
        rosterRoleReceivesAttendanceCapture(x.rosterRole) &&
        x.cohortId?.toString() === effectiveCohortId.toString() &&
        x.batchId?.toString() === effectiveBatchId.toString(),
    );
    const traineeById = new Map(scopedTrainees.map((x) => [x.id.toString(), x]));
    const existingRowsForDate = await prisma.traineeAttendanceDay.findMany({
      where: {
        trainingId,
        batchId: effectiveBatchId,
        sessionDate: { gte: sessionBounds.gte, lt: sessionBounds.lt },
      },
      select: { traineeId: true },
    });
    const existingTraineeIds = new Set(existingRowsForDate.map((x) => x.traineeId.toString()));

    const dedupedEntries = dedupeAttendanceEntries(parsed.data.entries);
    let inserted = 0;
    let skippedExisting = 0;
    let skippedIneligible = 0;
    const dryRun = parsed.data.dryRun === true;
    for (const e of dedupedEntries) {
      const row = traineeById.get(e.traineeId);
      if (!row || !row.batchId) {
        return void res.status(422).json({
          error: "One or more trainees are outside the selected delivery scope for attendance backfill.",
        });
      }
      if (existingTraineeIds.has(e.traineeId)) {
        skippedExisting++;
        continue;
      }
      if (
        !traineeEligibleForSessionDate({
          range: sessionRange,
          holidayDates,
          sessionDate,
          breakdowns,
          deliveryBatchId: effectiveBatchId,
          anchorStart,
          exemptDays,
          trainee: row,
        })
      ) {
        skippedIneligible++;
        continue;
      }
      if (!dryRun) {
        await upsertTraineeAttendanceDay(prisma, {
          projectId,
          trainingProviderId: tr.trainingProviderId,
          trainingId,
          cohortId: row.cohortId,
          batchId: row.batchId,
          traineeId: BigInt(e.traineeId),
          sessionDate,
          status: e.status,
          source: "manual_backfill",
        });
      }
      inserted++;
    }

    if (!dryRun) {
      await writeSubmissionEvent({
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        batchId: effectiveBatchId,
        action: "attendance_backfill_missing_rows",
        sourceType: "manual_backfill",
        sourceRef: parsed.data.sessionDate,
        payloadRaw: JSON.stringify(parsed.data),
        actorUserId: req.auth!.userId,
        meta: { inserted, skippedExisting, skippedIneligible },
      });
    }
    res.json({ ok: true, dryRun, inserted, skippedExisting, skippedIneligible, requested: dedupedEntries.length });
  },
);

/** ——— CSV import: trainee_unique_id, session_date, status ——— */

router.post(
  "/projects/:projectId/trainings/:trainingId/attendance/import-csv",
  requirePermission("submit:attendance", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const parsed = z.object({
      headers: z.array(z.string()).optional(),
      rows: z.array(z.record(z.string(), z.unknown())).max(10_000),
      dryRun: z.boolean().optional(),
      /** Calendar day selected in Attendance UI; every CSV row must match this date. */
      expectedSessionDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
    }).safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid body", details: parsed.error.flatten() });
    if (!attendanceImportHeadersAreExact((parsed.data.headers ?? []).map((h) => h.trim().toLowerCase()))) {
      return void res.status(422).json({
        error: "Attendance CSV must use the exact downloaded template headers and order.",
        validRows: 0,
        skippedRows: 0,
        errors: ["Expected headers: " + ATTENDANCE_IMPORT_HEADERS.join(", ")],
      });
    }

    const expectedSessionDate = parsed.data.expectedSessionDate;

    const tr = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      include: {
        trainees: {
          select: {
            id: true,
            traineeUniqueId: true,
            externalBeneficiaryId: true,
            cohortId: true,
            batchId: true,
            rosterRole: true,
            attendanceEligibleFrom: true,
          },
        },
      },
    });
    if (!tr) return void res.status(404).json({ error: "Training not found." });

    const importCohortRows = await prisma.trainingCohort.findMany({
      where: { trainingId, projectId },
      select: { id: true, code: true },
      orderBy: { id: "asc" },
    });
    if (importCohortRows.length === 0) {
      return void res.status(422).json({ error: "This training has no cohorts; cannot import attendance." });
    }

    const batchMetaById = new Map(
      (
        await prisma.trainingBatch.findMany({
          where: { trainingId, projectId },
          select: {
            id: true,
            cohortId: true,
            startDate: true,
            endDate: true,
            timelineAnchorDate: true,
            sessionWeekdays: true,
          },
        })
      ).map((b) => [b.id.toString(), b]),
    );

    const holidays = await prisma.projectHoliday.findMany({ where: { projectId }, select: { holidayDate: true } });
    const holidayDates = holidays.map((h) => h.holidayDate);
    const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);
    const csvBreakdowns = await prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, status: "approved" },
      select: { cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
    });

    const dryRun = parsed.data.dryRun === true;
    let valid = 0;
    const errors: string[] = [];
    const stagedRows: Array<{
      traineeId: bigint;
      cohortId: bigint | null;
      batchId: bigint;
      sessionDate: Date;
      status: "present" | "absent";
    }> = [];

    const traineeMap = new Map<string, (typeof tr.trainees)[number]>();
    for (const trainee of tr.trainees) {
      if (!rosterRoleReceivesAttendanceCapture(trainee.rosterRole)) continue;
      if (trainee.batchId == null) continue;
      const scopeKey = `${trainee.cohortId?.toString() ?? ""}:${trainee.batchId.toString()}`;
      const uid = trainee.traineeUniqueId.trim().toLowerCase();
      if (uid) traineeMap.set(`uid:${scopeKey}:${uid}`, trainee);
      const ext = (trainee.externalBeneficiaryId ?? "").trim().toLowerCase();
      if (ext) traineeMap.set(`ext:${scopeKey}:${ext}`, trainee);
    }

    const cohortIdByCode = new Map(importCohortRows.map((c) => [c.code, c.id] as const));
    const batchResolveCache = new Map<string, bigint>();

    for (let i = 0; i < parsed.data.rows.length; i++) {
      const row = parsed.data.rows[i] as Record<string, unknown>;
      const uid = String(row.trainee_unique_id ?? row.traineeUniqueId ?? "").trim();
      const extId = String(
        row.external_beneficiary_id ?? row.externalBeneficiaryId ?? row.provider_beneficiary_id ?? "",
      ).trim();
      const sd = String(row.session_date ?? row.sessionDate ?? "").trim();
      const st = String(row.status ?? "").trim().toLowerCase();
      if ((!uid && !extId) || !sd) {
        errors.push(`Row ${i + 1}: trainee_unique_id or external_beneficiary_id, and session_date are required`);
        continue;
      }
      const statusMap: Record<string, "present" | "absent"> = {
        present: "present",
        p: "present",
        y: "present",
        "1": "present",
        absent: "absent",
        a: "absent",
        n: "absent",
        "0": "absent",
      };
      const status = statusMap[st];
      if (!status) {
        errors.push(`Row ${i + 1}: invalid status`);
        continue;
      }

      let rowCohortId: bigint;
      if (importCohortRows.length > 1) {
        const cohortCode = csvCohortCodeRaw(row);
        const crs = csvCohortIdRaw(row);
        if (cohortCode) {
          const matchId = cohortIdByCode.get(cohortCode);
          if (!matchId) {
            errors.push(`Row ${i + 1}: unknown cohort_code '${cohortCode}' for this training.`);
            continue;
          }
          rowCohortId = matchId;
        } else {
          if (!/^\d+$/.test(crs)) {
            errors.push(`Row ${i + 1}: cohort_code is required when the training has multiple cohorts.`);
            continue;
          }
          rowCohortId = BigInt(crs);
          const cohortOk = importCohortRows.some((c) => c.id === rowCohortId);
          if (!cohortOk) {
            errors.push(`Row ${i + 1}: cohort not found for this training.`);
            continue;
          }
        }
      } else {
        rowCohortId = importCohortRows[0]!.id;
      }

      const { batchIdQuery, deliveryBatchCode } = csvBatchHints(row);
      let resolvedBatchId: bigint;
      try {
        const batchCacheKey = `${rowCohortId.toString()}:${batchIdQuery?.toString() ?? ""}:${deliveryBatchCode ?? ""}`;
        const cachedBatchId = batchResolveCache.get(batchCacheKey);
        if (cachedBatchId != null) {
          resolvedBatchId = cachedBatchId;
        } else {
          resolvedBatchId = await resolveTraineeDeliveryBatchId({
            prisma,
            cohortId: rowCohortId,
            explicitBatchId: batchIdQuery,
            deliveryBatchCode,
          });
          batchResolveCache.set(batchCacheKey, resolvedBatchId);
        }
      } catch (e) {
        errors.push(`Row ${i + 1}: ${(e as Error).message}`);
        continue;
      }

      const scopeKey = `${rowCohortId.toString()}:${resolvedBatchId.toString()}`;
      const traineeRow =
        (uid ? traineeMap.get(`uid:${scopeKey}:${uid.toLowerCase()}`) : undefined) ??
        (extId ? traineeMap.get(`ext:${scopeKey}:${extId.toLowerCase()}`) : undefined);
      if (!traineeRow || !traineeRow.batchId) {
        const idHint = uid || extId || "?";
        errors.push(
          `Row ${i + 1}: unknown trainee (${idHint}) for this cohort/delivery batch, or trainee is not on the attendance roster (active/reserve only).`,
        );
        continue;
      }

      const batchTimeline = batchMetaById.get(resolvedBatchId.toString());
      if (!batchTimeline) {
        errors.push(`Row ${i + 1}: delivery batch not found.`);
        continue;
      }
      const anchorStart = effectiveStartDate(batchTimeline.startDate, batchTimeline.timelineAnchorDate);
      const sessionRange: TrainingDateRange = {
        startDate: anchorStart,
        endDate: batchTimeline.endDate,
        sessionWeekdays: batchTimeline.sessionWeekdays ?? tr.sessionWeekdays,
      };

      const parsedSessionDate = parseAttendanceImportDate(sd);
      if (!parsedSessionDate) {
        errors.push(`Row ${i + 1}: invalid session_date '${sd}'. Use YYYY-MM-DD or re-download the template.`);
        continue;
      }
      if (parsedSessionDate.normalized !== expectedSessionDate) {
        errors.push(
          `Row ${i + 1}: session_date '${parsedSessionDate.normalized}' must match the selected calendar date '${expectedSessionDate}'.`,
        );
        continue;
      }
      const sessionDate = parsedSessionDate.date;
      if (isSessionDateExempt(sessionDate, anchorStart, exemptDays)) {
        const firstDay = firstAttendanceTrackingDay(anchorStart, exemptDays).toISOString().slice(0, 10);
        errors.push(
          `Row ${i + 1}: ${parsedSessionDate.normalized} is in the no-attendance startup period; attendance tracking starts ${firstDay}.`,
        );
        continue;
      }
      const blockedByBreakdown = findPrefetchedBreakdownBlock({
        breakdowns: csvBreakdowns,
        cohortId: rowCohortId,
        batchId: resolvedBatchId,
        sessionDate,
      });
      if (blockedByBreakdown) {
        errors.push(`Row ${i + 1}: ${parsedSessionDate.normalized} falls inside approved breakdown window (${blockedByBreakdown.scope}).`);
        continue;
      }
      if (!isScheduledSessionDate(sessionRange, holidayDates, sessionDate, new Date())) {
        errors.push(`Row ${i + 1}: ${parsedSessionDate.normalized} is not a scheduled session for this delivery batch`);
        continue;
      }
      if (
        !traineeEligibleForSessionDate({
          range: sessionRange,
          holidayDates,
          sessionDate,
          breakdowns: csvBreakdowns,
          deliveryBatchId: resolvedBatchId,
          anchorStart,
          exemptDays,
          trainee: traineeRow,
        })
      ) {
        errors.push(`Row ${i + 1}: trainee not eligible for session ${parsedSessionDate.normalized}`);
        continue;
      }
      stagedRows.push({
        traineeId: traineeRow.id,
        cohortId: traineeRow.cohortId,
        batchId: resolvedBatchId,
        sessionDate,
        status,
      });
      valid++;
    }

    if (errors.length > 0) {
      return void res.status(422).json({
        dryRun,
        validRows: 0,
        skippedRows: 0,
        errors: errors.slice(0, 200),
        error: "Attendance CSV import blocked: one or more rows are invalid. No rows were committed.",
      });
    }

    const dateKeysByBatch = new Map<string, Set<string>>();
    for (const e of stagedRows) {
      const bk = e.batchId.toString();
      const set = dateKeysByBatch.get(bk) ?? new Set<string>();
      set.add(sessionDateKey(e.sessionDate));
      dateKeysByBatch.set(bk, set);
    }

    if (!dryRun && dateKeysByBatch.size > 0) {
      for (const [bidStr, dateKeys] of dateKeysByBatch.entries()) {
        const incomingDateStrs = [...dateKeys].sort();
        const first = toDbDateOnly(incomingDateStrs[0]!);
        const last = toDbDateOnly(incomingDateStrs[incomingDateStrs.length - 1]!);
        const lastBounds = sessionDateQueryBounds(incomingDateStrs[incomingDateStrs.length - 1]!);
        const existingRows = await prisma.traineeAttendanceDay.findMany({
          where: {
            trainingId,
            batchId: BigInt(bidStr),
            sessionDate: { gte: first, lt: lastBounds.lt },
          },
          select: { sessionDate: true },
        });
        const incomingKeys = new Set(incomingDateStrs);
        const conflictDates = [
          ...new Set(existingRows.map((r) => sessionDateKey(r.sessionDate)).filter((k) => incomingKeys.has(k))),
        ];
        if (conflictDates.length > 0) {
          return void res.status(409).json({
            error: `Attendance already recorded for this delivery batch on date(s): ${conflictDates.slice(0, 10).join(", ")}.`,
          });
        }
      }
    }

    if (!dryRun) {
      const rowsToWrite = dedupeStagedAttendanceRows(stagedRows);
      const distinctBatches = [...new Set(rowsToWrite.map((r) => r.batchId.toString()))];
      try {
        await prisma.$transaction(async (tx) => {
          await tx.traineeAttendanceDay.createMany({
            data: rowsToWrite.map((e) => ({
              projectId,
              trainingProviderId: tr.trainingProviderId,
              trainingId,
              cohortId: e.cohortId,
              batchId: e.batchId,
              traineeId: e.traineeId,
              sessionDate: e.sessionDate,
              status: e.status,
              source: "csv_daily",
            })),
          });
        });
      } catch (e) {
        if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
          return void res.status(409).json({
            error: "Attendance already recorded for one or more trainees on this date for this delivery batch.",
          });
        }
        throw e;
      }

      // Audit after the attendance rows commit so a large CSV payload cannot roll back a successful import.
      await writeSubmissionEvent({
        projectId,
        trainingProviderId: tr.trainingProviderId,
        trainingId,
        cohortId: distinctBatches.length === 1 ? rowsToWrite[0]!.cohortId : null,
        batchId: distinctBatches.length === 1 ? rowsToWrite[0]!.batchId : null,
        action: "csv_import",
        sourceType: "csv_daily",
        sourceRef: null,
        payloadRaw: JSON.stringify({
          rowCount: parsed.data.rows.length,
          validRows: rowsToWrite.length,
          deliveryBatchIds: distinctBatches,
        }),
        actorUserId: req.auth!.userId,
        meta: { validRows: valid, skippedRows: 0, errorCount: 0, deliveryBatchIds: distinctBatches },
      });
    }

    res.json({ dryRun, validRows: valid, skippedRows: 0, errors: [] as string[] });
  },
);

export default router;
