import { Router, type Response } from "express";
import crypto from "crypto";
import bcrypt from "bcryptjs";
import { z } from "zod";
import { prisma } from "../prisma.js";
import { Prisma } from "@prisma/client";
import { requireAuth, type AuthedRequest } from "../middleware/auth.js";
import { requirePermission } from "../middleware/permissions.js";
import { sendProviderWelcomeEmail } from "../services/smtp.js";
import { parseSessionWeekdays } from "../services/attendanceCalendar.js";
import { writeAuditEvent } from "../services/auditEventService.js";
import {
  hasProjectAccess as hasProjectAccessPolicy,
  resolveProjectScope as resolveProjectScopePolicy,
  assertTpAssigned,
  enforceProviderScope,
  assertDeliveryScope,
  traineeDeliveryScopeWhere,
  filterCohortsForScope,
  filterBatchesForScope,
  filterTrainingsForScope,
} from "../services/scopePolicy.js";
import {
  ensureMainBatchForCohort,
  ensureCohortsForDeliverySites,
  ensureMainCohortAndBatchForTraining,
  resolveTraineeDeliveryBatchId,
  resolveTrainingScope,
} from "../services/trainingScopeGuards.js";
import {
  generateScopedTraineeUniqueId,
  isScopedTraineeUniqueId,
  normalizeProvidedTraineeUniqueId,
} from "../services/traineeId.js";
import { buildTraineeSearchOrFilters } from "../services/traineeSearch.js";
import {
  countsAsActiveCohortMember,
  parseRosterRole,
  rosterRoleIsTrackedMember,
  trackedRosterRoleFilter,
} from "../services/traineeRoster.js";
import {
  eligibilityProtocolWhere,
  normalizeEmploymentStatus,
  normalizeHighestEducation,
} from "../services/traineeEligibility.js";
import { traineeCountsByTrainingId } from "../services/trainingTraineeCounts.js";
import { computeRosterInsights } from "../services/rosterInsights.js";
import { canonicalPhoneKey, normalizePhone, phonePrimaryValidationError } from "../services/phoneNormalize.js";
import {
  normalizeEtCalendarDateText,
  parseTraineeFormCompletionDate,
  traineeRowLabel,
} from "../services/traineeImportDates.js";
import { executeTrainingPurge, previewTrainingPurge } from "../services/trainingPurge.js";
import { deleteTraineeWithCopy, traineeDeleteImpact } from "../services/traineeDelete.js";
import { buildProviderLocationBreakdown } from "../services/providerLocationBreakdown.js";
import {
  assertCanRegisterTrainees,
  countRegisteredTrainees,
  getProjectMaxOverenrollmentPercent,
  getProviderContract,
  serializeContractPayload,
} from "../services/providerContract.js";
import { assertRegistrationOpen, getRegistrationGateSnapshot } from "../services/registrationGate.js";
import { userHasEffectivePermission } from "../services/effectivePermissions.js";
import { toPercent } from "../services/reportTheme.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);
}

async function audit(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;
  meta?: Prisma.InputJsonValue;
  actorUserId?: bigint | null;
}) {
  await writeAuditEvent({
    projectId: args.projectId,
    trainingProviderId: args.trainingProviderId ?? null,
    trainingId: args.trainingId ?? null,
    cohortId: args.cohortId ?? null,
    batchId: args.batchId ?? null,
    module: "domain",
    action: args.action,
    sourceType: args.sourceType ?? null,
    sourceRef: args.sourceRef ?? null,
    payloadRaw: args.payloadRaw ?? null,
    meta: args.meta,
    actorUserId: args.actorUserId ?? null,
  });
}

// scope helpers moved to services/scopePolicy.ts (with local wrappers in this module)

function parseTraineeIdParam(raw: string): bigint | null {
  if (!/^\d+$/.test(String(raw ?? "").trim())) return null;
  return BigInt(raw);
}

function parseDeliveryLocationIds(raw: unknown): string[] {
  if (!Array.isArray(raw)) return [];
  const out: string[] = [];
  for (const x of raw) {
    const s = String(x).trim();
    if (/^\d+$/.test(s) && !out.includes(s)) out.push(s);
  }
  return out;
}

function normalizeDeliveryLocationIdsInput(args: {
  deliveryLocationIds?: string[] | undefined;
  locationId?: string | undefined;
}): string[] {
  const fromArray = (args.deliveryLocationIds ?? []).map((x) => String(x).trim()).filter((s) => /^\d+$/.test(s));
  if (fromArray.length > 0) return Array.from(new Set(fromArray));
  const legacy = args.locationId?.trim();
  if (legacy && /^\d+$/.test(legacy)) return [legacy];
  return [];
}

async function deliveryLocationsPayload(rawIds: unknown, fallbackLocationId: bigint | null) {
  const ids = parseDeliveryLocationIds(rawIds);
  const effectiveIds = ids.length > 0 ? ids : fallbackLocationId ? [fallbackLocationId.toString()] : [];
  if (effectiveIds.length === 0) {
    return { deliveryLocationIds: [] as string[], deliveryLocations: [] as Array<{ id: string; name: string }> };
  }
  const rows = await prisma.location.findMany({
    where: { id: { in: effectiveIds.map((id) => BigInt(id)) } },
    select: { id: true, name: true },
  });
  const byId = new Map(rows.map((r) => [r.id.toString(), r]));
  const deliveryLocations = effectiveIds
    .map((id) => {
      const row = byId.get(id);
      return row ? { id: asId(row.id), name: row.name } : null;
    })
    .filter((x): x is { id: string; name: string } => x != null);
  return { deliveryLocationIds: effectiveIds, deliveryLocations };
}

async function trainingDeliverySiteIds(trainingId: bigint, projectId: bigint): Promise<string[]> {
  const training = await prisma.training.findFirst({
    where: { id: trainingId, projectId },
    select: { deliveryLocationIds: true, locationId: true },
  });
  if (!training) return [];
  const fromJson = parseDeliveryLocationIds(training.deliveryLocationIds);
  if (fromJson.length > 0) return fromJson;
  return training.locationId ? [training.locationId.toString()] : [];
}

async function assertCohortLocationInTrainingDeliverySites(args: {
  trainingId: bigint;
  projectId: bigint;
  locationId: bigint | null | undefined;
}) {
  const effective = await trainingDeliverySiteIds(args.trainingId, args.projectId);
  if (effective.length > 1 && !args.locationId) {
    const err = new Error(
      "Delivery location is required for this cohort. The training is offered in multiple cities — assign each cohort to one site.",
    ) as Error & { status?: number };
    err.status = 422;
    throw err;
  }
  if (!args.locationId) return;
  if (effective.length === 0) return;
  if (!effective.includes(args.locationId.toString())) {
    const err = new Error("Cohort location must be one of the training delivery sites.") as Error & { status?: number };
    err.status = 422;
    throw err;
  }
}

const optionalEmailField = z.preprocess(
  (value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
  z.string().email().optional(),
);

async function findConflictingTraineeByPhone(args: {
  projectId: bigint;
  phonePrimary?: string | null;
  excludeTraineeId?: bigint | null;
}): Promise<{ id: bigint; phonePrimary: string | null; firstName: string } | null> {
  const key = canonicalPhoneKey(args.phonePrimary);
  if (!key) return null;
  const rows = await prisma.trainee.findMany({
    where: {
      projectId: args.projectId,
      phonePrimary: { not: null },
      ...(args.excludeTraineeId ? { id: { not: args.excludeTraineeId } } : {}),
    },
    select: { id: true, phonePrimary: true, firstName: true, fatherName: true },
    take: 5000,
  });
  for (const r of rows) {
    if (canonicalPhoneKey(r.phonePrimary) === key) {
      return { id: r.id, phonePrimary: r.phonePrimary, firstName: [r.firstName, r.fatherName].filter(Boolean).join(" ") };
    }
  }
  return null;
}

async function assertPhonePrimaryUniqueInProject(args: {
  projectId: bigint;
  phonePrimary?: string | null;
  excludeTraineeId?: bigint | null;
}) {
  const conflict = await findConflictingTraineeByPhone(args);
  if (conflict) {
    const who = conflict.firstName || `trainee #${conflict.id}`;
    throw new Error(`phonePrimary already exists in this project (${who}, stored as ${conflict.phonePrimary})`);
  }
}

function normalizeExternalBeneficiaryId(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const normalized = value.trim();
  return normalized.length ? normalized : null;
}

async function assertExternalBeneficiaryIdUniqueInProviderScope(args: {
  projectId: bigint;
  trainingProviderId: bigint;
  externalBeneficiaryId?: string | null;
  excludeTraineeId?: bigint | null;
}) {
  const externalBeneficiaryId = normalizeExternalBeneficiaryId(args.externalBeneficiaryId);
  if (!externalBeneficiaryId) return;
  const existing = await prisma.trainee.findFirst({
    where: {
      projectId: args.projectId,
      trainingProviderId: args.trainingProviderId,
      externalBeneficiaryId,
      ...(args.excludeTraineeId ? { id: { not: args.excludeTraineeId } } : {}),
    },
    select: { id: true, traineeUniqueId: true },
  });
  if (!existing) return;
  throw new Error(
    `externalBeneficiaryId "${externalBeneficiaryId}" is already used by trainee ${existing.traineeUniqueId}.`,
  );
}

async function assertProjectRegistrationOpen(
  projectId: bigint,
  trainingProviderId?: bigint | null,
  area: "trainee" | "structure" = "trainee",
) {
  await assertRegistrationOpen(projectId, trainingProviderId, area);
}

async function guardStructureForTraining(projectId: bigint, trainingId: bigint) {
  const training = await prisma.training.findFirst({
    where: { id: trainingId, projectId },
    select: { trainingProviderId: true },
  });
  if (!training) {
    const err = new Error("Training not found.") as Error & { status?: number };
    err.status = 404;
    throw err;
  }
  await assertProjectRegistrationOpen(projectId, training.trainingProviderId, "structure");
}

async function assertNoVerificationRunForProvider(projectId: bigint, trainingProviderId: bigint) {
  const runs = await prisma.verificationSampleRun.count({
    where: { projectId, trainingProviderId },
  });
  if (runs > 0) {
    const err = new Error(
      "Training/cohort creation is blocked because verification has already started for this training provider in this project.",
    ) as Error & { status?: number };
    err.status = 422;
    throw err;
  }
}

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

function dateOnlyUtc(value: Date | string): Date {
  const d = typeof value === "string" ? new Date(value) : new Date(value);
  return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
}

function parseDateOnlyInput(value: string): Date {
  const ymd = value.slice(0, 10);
  if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) return dateOnlyUtc(value);
  return new Date(`${ymd}T12:00:00.000Z`);
}

function toDateOnlyYmd(value: Date): string {
  const y = value.getFullYear();
  const m = String(value.getMonth() + 1).padStart(2, "0");
  const d = String(value.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

function isDateOnlyNoonUtc(value: Date): boolean {
  return (
    value.getUTCHours() === 12 &&
    value.getUTCMinutes() === 0 &&
    value.getUTCSeconds() === 0 &&
    value.getUTCMilliseconds() === 0
  );
}

function normalizeDateOnlyNoonUtc(value: Date): Date {
  return new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate(), 12, 0, 0, 0));
}

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

function diffDaysInclusive(start: Date, end: Date): number {
  const ms = dateOnlyUtc(end).getTime() - dateOnlyUtc(start).getTime();
  return Math.max(0, Math.floor(ms / (24 * 60 * 60 * 1000)) + 1);
}

function diffDays(start: Date, end: Date): number {
  const ms = dateOnlyUtc(end).getTime() - dateOnlyUtc(start).getTime();
  return Math.floor(ms / (24 * 60 * 60 * 1000));
}

async function trainingWindowMaxEndWithBreakdowns(prismaTx: typeof prisma, args: {
  projectId: bigint;
  trainingId: bigint;
  trainingBaseEnd: Date;
  cohortId: bigint | null;
  batchId: bigint | null;
}): Promise<Date> {
  const [trainingLevelBreakdowns, cohortBreakdowns, batchBreakdowns] = await Promise.all([
    prismaTx.trainingBreakdown.findMany({
      where: { projectId: args.projectId, trainingId: args.trainingId, cohortId: null, batchId: null, status: "approved" },
      select: { breakStartDate: true, breakEndDate: true },
    }),
    args.cohortId
      ? prismaTx.trainingBreakdown.findMany({
          where: { projectId: args.projectId, trainingId: args.trainingId, cohortId: args.cohortId, batchId: null, status: "approved" },
          select: { breakStartDate: true, breakEndDate: true },
        })
      : Promise.resolve([]),
    args.batchId
      ? prismaTx.trainingBreakdown.findMany({
          where: { projectId: args.projectId, trainingId: args.trainingId, batchId: args.batchId, status: "approved" },
          select: { breakStartDate: true, breakEndDate: true },
        })
      : Promise.resolve([]),
  ]);
  const extensionDays = [...trainingLevelBreakdowns, ...cohortBreakdowns, ...batchBreakdowns].reduce(
    (sum, b) => sum + diffDaysInclusive(b.breakStartDate, b.breakEndDate),
    0,
  );
  const maxEnd = dateOnlyUtc(args.trainingBaseEnd);
  maxEnd.setUTCDate(maxEnd.getUTCDate() + extensionDays);
  return maxEnd;
}

router.get("/master-data/training-durations", async (_req, res) => {
  const items = await prisma.trainingDuration.findMany({ orderBy: [{ sortOrder: "asc" }, { months: "asc" }] });
  res.json({ items: items.map((i: { id: bigint; label: string; months: number; sortOrder: number; isActive: boolean }) => ({ id: asId(i.id), label: i.label, months: i.months, sortOrder: i.sortOrder, isActive: i.isActive })) });
});

router.post("/master-data/training-durations", requirePermission("admin:settings"), async (req, res) => {
  const parsed = z.object({ label: z.string().min(1), months: z.number().int().positive(), sortOrder: z.number().int().default(0), isActive: z.boolean().default(true) }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const created = await prisma.trainingDuration.create({ data: parsed.data });
  res.json({ item: { id: asId(created.id), label: created.label, months: created.months, sortOrder: created.sortOrder, isActive: created.isActive } });
});

router.put("/master-data/training-durations/:id", requirePermission("admin:settings"), async (req, res) => {
  const id = BigInt(req.params.id);
  const parsed = z.object({ label: z.string().min(1), months: z.number().int().positive(), sortOrder: z.number().int().default(0), isActive: z.boolean().default(true) }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const updated = await prisma.trainingDuration.update({ where: { id }, data: parsed.data });
  res.json({ item: { id: asId(updated.id), label: updated.label, months: updated.months, sortOrder: updated.sortOrder, isActive: updated.isActive } });
});

router.delete("/master-data/training-durations/:id", requirePermission("admin:settings"), async (req, res) => {
  await prisma.trainingDuration.delete({ where: { id: BigInt(req.params.id) } });
  res.json({ ok: true });
});

router.get("/master-data/locations", async (_req, res) => {
  const items = await prisma.location.findMany({ orderBy: { name: "asc" } });
  res.json({ items: items.map((i: { id: bigint; name: string; code: string; isActive: boolean }) => ({ id: asId(i.id), name: i.name, code: i.code, isActive: i.isActive })) });
});

router.post("/master-data/locations", requirePermission("admin:settings"), async (req, res) => {
  const parsed = z.object({ name: z.string().min(1), code: z.string().min(1), isActive: z.boolean().default(true) }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const created = await prisma.location.create({ data: { name: parsed.data.name.trim(), code: parsed.data.code.trim().toUpperCase(), isActive: parsed.data.isActive } });
  res.json({ item: { id: asId(created.id), name: created.name, code: created.code, isActive: created.isActive } });
});

router.put("/master-data/locations/:id", requirePermission("admin:settings"), async (req, res) => {
  const id = BigInt(req.params.id);
  const parsed = z.object({ name: z.string().min(1), code: z.string().min(1), isActive: z.boolean().default(true) }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const updated = await prisma.location.update({ where: { id }, data: { name: parsed.data.name.trim(), code: parsed.data.code.trim().toUpperCase(), isActive: parsed.data.isActive } });
  res.json({ item: { id: asId(updated.id), name: updated.name, code: updated.code, isActive: updated.isActive } });
});

router.delete("/master-data/locations/:id", requirePermission("admin:settings"), async (req, res) => {
  await prisma.location.delete({ where: { id: BigInt(req.params.id) } });
  res.json({ ok: true });
});

router.get("/projects/:projectId/providers", requirePermission("view:providers", { 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 to this project." });
  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 items = await prisma.trainingProvider.findMany({
    where: { projectId, ...(scope.providerId ? { id: scope.providerId } : {}) },
    include: { trainings: { select: { id: true } } },
    orderBy: { id: "desc" },
  });
  const traineeCounts = await prisma.trainee.groupBy({
    by: ["trainingProviderId", "rosterRole"],
    where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    _count: { _all: true },
  });
  const countsByProvider = new Map<string, { active: number; reserve: number; total: number }>();
  for (const r of traineeCounts) {
    const key = r.trainingProviderId.toString();
    const cur = countsByProvider.get(key) ?? { active: 0, reserve: 0, total: 0 };
    const c = r._count._all;
    if (r.rosterRole === "active") cur.active += c;
    else if (r.rosterRole === "reserve") cur.reserve += c;
    cur.total += c;
    countsByProvider.set(key, cur);
  }
  res.json({ items: items.map((p) => {
    const counts = countsByProvider.get(p.id.toString()) ?? { active: 0, reserve: 0, total: 0 };
    return {
      id: asId(p.id),
      tpCode: p.tpCode,
      name: p.name,
      contactName: p.contactName,
      contactEmail: p.contactEmail,
      contactPhone: p.contactPhone,
      requireExternalBeneficiaryId: p.requireExternalBeneficiaryId,
      registrationClosed: Boolean(p.registrationClosedAt),
      trainingsCount: p.trainings.length,
      traineesCount: counts.active,
      traineesActiveCount: counts.active,
      traineesReserveCount: counts.reserve,
      traineesTotalCount: counts.total,
    };
  }) });
});

router.get("/projects/:projectId/providers/:providerId", requirePermission("view:providers", { 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 to this project." });
  const scope = await resolveScope(projectId, req.auth!.userId);
  try { assertTpAssigned(scope); enforceProviderScope(scope, providerId); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
  const p = await prisma.trainingProvider.findFirst({
    where: { id: providerId, projectId },
    include: {
      trainings: { select: { id: true } },
      trainees: { select: { id: true } },
      registrationClosedByUser: { select: { name: true, email: true } },
    },
  });
  if (!p) return void res.status(404).json({ error: "Provider not found." });
  const counts = await prisma.trainee.groupBy({
    by: ["rosterRole"],
    where: { projectId, trainingProviderId: providerId },
    _count: { _all: true },
  });
  let active = 0;
  let reserve = 0;
  let total = 0;
  for (const r of counts) {
    const c = r._count._all;
    if (r.rosterRole === "active") active += c;
    else if (r.rosterRole === "reserve") reserve += c;
    total += c;
  }
  res.json({
    item: {
      id: asId(p.id),
      tpCode: p.tpCode,
      name: p.name,
      contactName: p.contactName,
      contactEmail: p.contactEmail,
      contactPhone: p.contactPhone,
      requireExternalBeneficiaryId: p.requireExternalBeneficiaryId,
      registrationClosed: Boolean(p.registrationClosedAt),
      registrationClosedAt: p.registrationClosedAt?.toISOString() ?? null,
      registrationCloseNote: p.registrationCloseNote ?? null,
      registrationClosedByName: p.registrationClosedByUser?.name ?? null,
      trainingsCount: p.trainings.length,
      traineesCount: active,
      traineesActiveCount: active,
      traineesReserveCount: reserve,
      traineesTotalCount: total,
      status: "active",
    },
  });
});

router.get(
  "/projects/:projectId/providers/:providerId/registration",
  requirePermission("view:providers", { 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 to this project." });
    }
    const scope = await resolveScope(projectId, req.auth!.userId);
    try {
      assertTpAssigned(scope);
      enforceProviderScope(scope, providerId);
    } catch (e) {
      return void res.status((e as any).status ?? 403).json({ error: (e as Error).message });
    }
    const provider = await prisma.trainingProvider.findFirst({
      where: { id: providerId, projectId },
      select: {
        id: true,
        name: true,
        registrationClosedAt: true,
        registrationCloseNote: true,
        registrationClosedByUserId: true,
        registrationClosedByUser: { select: { name: true, email: true } },
      },
    });
    if (!provider) return void res.status(404).json({ error: "Provider not found." });

    const gate = await getRegistrationGateSnapshot(projectId, providerId);
    res.json({
      item: {
        providerId: provider.id.toString(),
        providerName: provider.name,
        isClosed: Boolean(provider.registrationClosedAt),
        closedAt: provider.registrationClosedAt?.toISOString() ?? null,
        closedByUserId: provider.registrationClosedByUserId?.toString() ?? null,
        closedByName: provider.registrationClosedByUser?.name ?? null,
        closedByEmail: provider.registrationClosedByUser?.email ?? null,
        note: provider.registrationCloseNote ?? null,
        effective: gate,
      },
    });
  },
);

router.put(
  "/projects/:projectId/providers/:providerId/registration",
  requirePermission("manage:tps", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const parsed = z
      .object({
        isClosed: z.boolean(),
        note: z.string().max(500).optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) {
      return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    }

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

    const note = parsed.data.note?.trim() || null;
    const updated = await prisma.trainingProvider.update({
      where: { id: providerId },
      data: parsed.data.isClosed
        ? {
            registrationClosedAt: new Date(),
            registrationClosedByUserId: req.auth!.userId,
            registrationCloseNote: note,
          }
        : {
            registrationClosedAt: null,
            registrationClosedByUserId: null,
            registrationCloseNote: note,
          },
      select: {
        id: true,
        name: true,
        registrationClosedAt: true,
        registrationCloseNote: true,
        registrationClosedByUserId: true,
        registrationClosedByUser: { select: { name: true, email: true } },
      },
    });

    await audit({
      projectId,
      trainingProviderId: providerId,
      action: parsed.data.isClosed ? "provider_registration_closed" : "provider_registration_opened",
      sourceType: "training_provider",
      sourceRef: providerId.toString(),
      payloadRaw: JSON.stringify({
        tpCode: provider.tpCode,
        providerName: provider.name,
        isClosed: parsed.data.isClosed,
        note: updated.registrationCloseNote ?? null,
      }),
      actorUserId: req.auth!.userId,
    });

    const gate = await getRegistrationGateSnapshot(projectId, providerId);
    res.json({
      item: {
        providerId: updated.id.toString(),
        providerName: updated.name,
        isClosed: Boolean(updated.registrationClosedAt),
        closedAt: updated.registrationClosedAt?.toISOString() ?? null,
        closedByUserId: updated.registrationClosedByUserId?.toString() ?? null,
        closedByName: updated.registrationClosedByUser?.name ?? null,
        closedByEmail: updated.registrationClosedByUser?.email ?? null,
        note: updated.registrationCloseNote ?? null,
        effective: gate,
      },
    });
  },
);

router.get(
  "/projects/:projectId/providers/:providerId/trainee-location-breakdown",
  requirePermission("view:providers", { 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 to this project." });
    }
    const scope = await resolveScope(projectId, req.auth!.userId);
    try {
      assertTpAssigned(scope);
      enforceProviderScope(scope, providerId);
    } catch (e) {
      return void res.status((e as any).status ?? 403).json({ error: (e as Error).message });
    }
    const exists = await prisma.trainingProvider.findFirst({
      where: { id: providerId, projectId },
      select: { id: true },
    });
    if (!exists) return void res.status(404).json({ error: "Provider not found." });

    const breakdown = await buildProviderLocationBreakdown(prisma, projectId, providerId);
    res.json(breakdown);
  },
);

router.get(
  "/projects/:projectId/providers/:providerId/contract",
  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 to this project." });
    }
    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 userId = req.auth!.userId;
    const canRead =
      scope.providerId === providerId ||
      (await userHasEffectivePermission(prisma, userId, projectId, "manage:trainings")) ||
      (await userHasEffectivePermission(prisma, userId, projectId, "view:providers"));
    if (!canRead) {
      return void res.status(403).json({ error: "Missing permission to view contract." });
    }
    const exists = await prisma.trainingProvider.findFirst({
      where: { id: providerId, projectId },
      select: { id: true },
    });
    if (!exists) return void res.status(404).json({ error: "Provider not found." });
    const [contract, registered, maxOverPct] = await Promise.all([
      getProviderContract(prisma, projectId, providerId),
      countRegisteredTrainees(prisma, projectId, providerId),
      getProjectMaxOverenrollmentPercent(prisma, projectId),
    ]);
    res.json({ item: serializeContractPayload(contract, registered, maxOverPct) });
  },
);

router.put(
  "/projects/:projectId/providers/:providerId/contract",
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const providerId = BigInt(req.params.providerId);
    const parsed = z
      .object({
        contractTarget: z.number().int().positive(),
      })
      .safeParse(req.body);
    if (!parsed.success) {
      return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    }
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) {
      return void res.status(403).json({ error: "No access to this project." });
    }
    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 userId = req.auth!.userId;
    const canWrite =
      scope.providerId === providerId ||
      (await userHasEffectivePermission(prisma, userId, projectId, "manage:tps"));
    if (!canWrite) {
      return void res.status(403).json({ error: "Missing permission to update contract." });
    }
    const provider = await prisma.trainingProvider.findFirst({
      where: { id: providerId, projectId },
      select: { id: true },
    });
    if (!provider) return void res.status(404).json({ error: "Provider not found." });
    const existing = await getProviderContract(prisma, projectId, providerId);
    if (existing) {
      return void res.status(409).json({
        error: "Contract target is already set and cannot be changed.",
        code: "contract_immutable",
      });
    }
    const row = await prisma.trainingProviderContract.create({
      data: {
        projectId,
        trainingProviderId: providerId,
        contractTarget: parsed.data.contractTarget,
        setByUserId: req.auth!.userId,
      },
    });
    const [registered, maxOverPct] = await Promise.all([
      countRegisteredTrainees(prisma, projectId, providerId),
      getProjectMaxOverenrollmentPercent(prisma, projectId),
    ]);
    await audit({
      projectId,
      trainingProviderId: providerId,
      action: "provider_contract_set",
      sourceType: "provider_contract",
      sourceRef: row.id.toString(),
      payloadRaw: JSON.stringify(parsed.data),
      actorUserId: req.auth!.userId,
    });
    res.json({
      item: serializeContractPayload(
        {
          projectId: row.projectId,
          trainingProviderId: row.trainingProviderId,
          contractTarget: row.contractTarget,
          effectiveFrom: row.effectiveFrom,
          notes: row.notes,
        },
        registered,
        maxOverPct,
      ),
    });
  },
);

router.get("/projects/:projectId/my-provider", 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 to this project." });
  const scope = await resolveScope(projectId, req.auth!.userId);
  if (scope.role !== "tp") return void res.status(403).json({ error: "Only TP users can access my-provider endpoint." });
  try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
  const providerId = scope.providerId!;
  const p = await prisma.trainingProvider.findFirst({
    where: { id: providerId, projectId },
    include: { trainings: { select: { id: true } }, trainees: { select: { id: true } } },
  });
  if (!p) return void res.status(404).json({ error: "Provider not found." });
  const counts = await prisma.trainee.groupBy({
    by: ["rosterRole"],
    where: { projectId, trainingProviderId: providerId },
    _count: { _all: true },
  });
  let active = 0;
  let reserve = 0;
  let total = 0;
  for (const r of counts) {
    const c = r._count._all;
    if (r.rosterRole === "active") active += c;
    else if (r.rosterRole === "reserve") reserve += c;
    total += c;
  }
  res.json({
    item: {
      id: asId(p.id),
      tpCode: p.tpCode,
      name: p.name,
      contactName: p.contactName,
      contactEmail: p.contactEmail,
      contactPhone: p.contactPhone,
      requireExternalBeneficiaryId: p.requireExternalBeneficiaryId,
      trainingsCount: p.trainings.length,
      traineesCount: active,
      traineesActiveCount: active,
      traineesReserveCount: reserve,
      traineesTotalCount: total,
      status: "active",
    },
  });
});

router.post("/projects/:projectId/providers", requirePermission("manage:tps", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const parsed = z.object({
    tpCode: z.string().min(1).max(50),
    name: z.string().min(1).max(255),
    accountEmail: z.string().email(),
    contactName: z.string().optional(),
    contactEmail: z.string().email().optional(),
    contactPhone: z.string().optional(),
    requireExternalBeneficiaryId: z.boolean().optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const accountEmail = parsed.data.accountEmail.trim().toLowerCase();

  const existing = await prisma.user.findUnique({ where: { email: accountEmail }, select: { id: true } });
  if (existing) {
    return void res.status(422).json({ error: "Account email already exists. Use a different email." });
  }

  const temporaryPassword = crypto.randomBytes(8).toString("base64url");
  const passwordHash = await bcrypt.hash(temporaryPassword, 12);

  const created = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
    const user = await tx.user.create({
      data: {
        name: parsed.data.contactName?.trim() || parsed.data.name.trim(),
        email: accountEmail,
        password: passwordHash,
      },
      select: { id: true },
    });
    await tx.$executeRaw`UPDATE users SET must_change_password = 1, password_changed_at = NULL WHERE id = ${user.id}`;

    const provider = await tx.trainingProvider.create({
      data: {
        projectId,
        userId: user.id,
        tpCode: parsed.data.tpCode.trim().toUpperCase(),
        name: parsed.data.name.trim(),
        contactName: parsed.data.contactName?.trim() || null,
        contactEmail: parsed.data.contactEmail?.trim().toLowerCase() || null,
        contactPhone: parsed.data.contactPhone?.trim() || null,
        requireExternalBeneficiaryId: parsed.data.requireExternalBeneficiaryId === true,
      },
      select: { id: true, name: true },
    });

    await tx.projectUser.create({
      data: {
        projectId,
        userId: user.id,
        projectRole: "tp",
      },
      select: { id: true },
    });

    await tx.tpStaffMembership.create({
      data: {
        projectId,
        trainingProviderId: provider.id,
        userId: user.id,
        staffRole: "tp_org_admin",
        invitedByUserId: req.auth!.userId,
        deliveryScopes: {
          create: [{ scopeLevel: "provider", trainingId: null, cohortId: null, batchId: null }],
        },
      },
    });

    return { provider, user };
  });

  try {
    const mail = await sendProviderWelcomeEmail(prisma, accountEmail, created.provider.name, temporaryPassword);
    if (mail.mode === "log") {
      return void res.status(201).json({
        item: { id: asId(created.provider.id) },
        warning: "MAIL_MODE=log is enabled. Credentials were logged on server, not emailed.",
      });
    }
  } catch (e) {
    const detail = e instanceof Error ? e.message : "unknown provider email error";
    console.error("[providers/create] provider created but welcome email failed:", detail);
    // Account is created; return warning so admin can resend after SMTP is fixed.
    return void res.status(201).json({
      item: { id: asId(created.provider.id) },
      warning: detail,
    });
  }

  await audit({
    projectId,
    trainingProviderId: created.provider.id,
    action: "provider_created",
    sourceType: "provider",
    sourceRef: created.provider.id.toString(),
    payloadRaw: JSON.stringify({ tpCode: parsed.data.tpCode.trim().toUpperCase(), name: created.provider.name }),
    actorUserId: req.auth!.userId,
  });
  res.json({ item: { id: asId(created.provider.id) }, credentialsSent: true });
});

router.put("/projects/:projectId/providers/:providerId", requirePermission("manage:tps", { projectIdParam: "projectId" }), async (req, res) => {
  const projectId = BigInt(req.params.projectId);
  const providerId = BigInt(req.params.providerId);
  const parsed = z.object({
    tpCode: z.string().min(1).max(50),
    name: z.string().min(1).max(255),
    contactName: z.string().optional(),
    contactEmail: z.string().email().optional(),
    contactPhone: z.string().optional(),
    requireExternalBeneficiaryId: z.boolean().optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const exists = await prisma.trainingProvider.findFirst({ where: { id: providerId, projectId }, select: { id: true } });
  if (!exists) return void res.status(404).json({ error: "Provider not found." });
  const updated = await prisma.trainingProvider.update({
    where: { id: providerId },
    data: {
      tpCode: parsed.data.tpCode.trim().toUpperCase(),
      name: parsed.data.name.trim(),
      contactName: parsed.data.contactName?.trim() || null,
      contactEmail: parsed.data.contactEmail?.trim().toLowerCase() || null,
      contactPhone: parsed.data.contactPhone?.trim() || null,
      requireExternalBeneficiaryId: parsed.data.requireExternalBeneficiaryId === true,
    },
  });
  res.json({ item: { id: asId(updated.id) } });
});

router.delete("/projects/:projectId/providers/:providerId", requirePermission("manage:tps", { projectIdParam: "projectId" }), async (req, res) => {
  const providerId = BigInt(req.params.providerId);
  const projectId = BigInt(req.params.projectId);
  const exists = await prisma.trainingProvider.findFirst({ where: { id: providerId, projectId }, select: { id: true } });
  if (!exists) return void res.status(404).json({ error: "Provider not found." });
  await prisma.trainingProvider.delete({ where: { id: providerId } });
  res.json({ ok: true });
});

router.get("/projects/:projectId/training-programs", requirePermission("view:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  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 items = await prisma.trainingProgram.findMany({
    where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    include: { trainingProvider: { select: { id: true, tpCode: true, name: true } }, trainings: { select: { id: true } } },
    orderBy: { id: "desc" },
  });
  res.json({
    items: items.map((p) => ({
      id: asId(p.id),
      code: p.code,
      name: p.name,
      trainingType: p.trainingType,
      status: p.status,
      notes: p.notes,
      provider: { id: asId(p.trainingProvider.id), tpCode: p.trainingProvider.tpCode, name: p.trainingProvider.name },
      cohortsCount: p.trainings.length,
    })),
  });
});

router.post("/projects/:projectId/training-programs", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const parsed = z.object({
    trainingProviderId: z.string().optional(),
    code: z.string().optional(),
    name: z.string().min(1),
    trainingType: z.string().optional(),
    status: z.string().optional(),
    notes: z.string().optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  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 reqProviderId = parsed.data.trainingProviderId ? BigInt(parsed.data.trainingProviderId) : null;
  const providerId = scope.providerId ?? reqProviderId;
  if (!providerId) return void res.status(400).json({ error: "trainingProviderId is required." });
  try {
    await assertProjectRegistrationOpen(projectId, providerId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const created = await prisma.trainingProgram.create({
    data: {
      projectId,
      trainingProviderId: providerId,
      code: parsed.data.code?.trim() || null,
      name: parsed.data.name.trim(),
      trainingType: parsed.data.trainingType?.trim() || null,
      status: parsed.data.status?.trim() || "active",
      notes: parsed.data.notes?.trim() || null,
    },
  });
  res.status(201).json({ item: { id: asId(created.id) } });
});

router.get("/projects/:projectId/trainings", requirePermission("view:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  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 items = await prisma.training.findMany({
    where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    include: {
      trainingProvider: true,
      trainingProgram: true,
      location: true,
      trainingDuration: true,
      cohorts: { select: { id: true } },
    },
    orderBy: { id: "desc" },
  });
  const scopedItems = filterTrainingsForScope(scope, items);
  const rosterCounts = await traineeCountsByTrainingId(prisma, {
    projectId,
    trainingProviderId: scope.providerId ?? undefined,
    trainingIds: scopedItems.map((t) => t.id),
  });
  res.json({ items: scopedItems.map((t: {
    id: bigint; title: string; trainingType: string; status: string; startDate: Date; endDate: Date; timelineAnchorDate: Date | null; intakeTarget: number | null; notes: string | null; sessionWeekdays: unknown;
    trainingProvider: { id: bigint; tpCode: string; name: string }; trainingProgram: { id: bigint; name: string } | null; location: { id: bigint; name: string } | null;
    trainingDuration: { id: bigint; label: string; months: number } | null; cohorts: Array<{ id: bigint }>;
  }) => {
    const counts = rosterCounts.get(t.id.toString()) ?? { active: 0, reserve: 0, total: 0 };
    return ({
    id: asId(t.id),
    title: t.title,
    trainingType: t.trainingType,
    status: t.status,
    startDate: toDateOnlyYmd(t.startDate),
    endDate: toDateOnlyYmd(t.endDate),
    timelineAnchorDate: t.timelineAnchorDate ? t.timelineAnchorDate.toISOString().slice(0, 10) : null,
    intakeTarget: t.intakeTarget,
    notes: t.notes,
    sessionWeekdays: parseSessionWeekdays(t.sessionWeekdays),
    deliveryLocationIds: parseDeliveryLocationIds((t as { deliveryLocationIds?: unknown }).deliveryLocationIds).length
      ? parseDeliveryLocationIds((t as { deliveryLocationIds?: unknown }).deliveryLocationIds)
      : t.location
        ? [asId(t.location.id)]
        : [],
    provider: { id: asId(t.trainingProvider.id), tpCode: t.trainingProvider.tpCode, name: t.trainingProvider.name },
    trainingProgram: t.trainingProgram ? { id: asId(t.trainingProgram.id), name: t.trainingProgram.name } : null,
    location: t.location ? { id: asId(t.location.id), name: t.location.name } : null,
    trainingDuration: t.trainingDuration ? { id: asId(t.trainingDuration.id), label: t.trainingDuration.label, months: t.trainingDuration.months } : null,
    traineesCount: counts.active,
    traineesActiveCount: counts.active,
    traineesReserveCount: counts.reserve,
    traineesTotalCount: counts.total,
    cohortsCount: t.cohorts.length,
  });
  }) });
});

router.get("/projects/:projectId/trainings/:trainingId", requirePermission("view:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  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 t = await prisma.training.findFirst({
    where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    include: { trainingProvider: true, trainingProgram: true, location: true, trainingDuration: true },
  });
  if (!t) return void res.status(404).json({ error: "Training not found." });
  const deliverySites = await deliveryLocationsPayload(t.deliveryLocationIds, t.locationId);
  const rosterMap = await traineeCountsByTrainingId(prisma, { projectId, trainingIds: [t.id] });
  const counts = rosterMap.get(t.id.toString()) ?? { active: 0, reserve: 0, total: 0 };
  res.json({
    item: {
      id: asId(t.id),
      title: t.title,
      trainingType: t.trainingType,
      status: t.status,
      startDate: toDateOnlyYmd(t.startDate),
      endDate: toDateOnlyYmd(t.endDate),
      timelineAnchorDate: t.timelineAnchorDate ? t.timelineAnchorDate.toISOString().slice(0, 10) : null,
      intakeTarget: t.intakeTarget,
      notes: t.notes,
      sessionWeekdays: parseSessionWeekdays(t.sessionWeekdays),
      ...deliverySites,
      provider: { id: asId(t.trainingProvider.id), tpCode: t.trainingProvider.tpCode, name: t.trainingProvider.name },
      trainingProgram: t.trainingProgram ? { id: asId(t.trainingProgram.id), name: t.trainingProgram.name } : null,
      location: t.location ? { id: asId(t.location.id), name: t.location.name } : null,
      trainingDuration: t.trainingDuration ? { id: asId(t.trainingDuration.id), label: t.trainingDuration.label, months: t.trainingDuration.months } : null,
      traineesCount: counts.active,
      traineesActiveCount: counts.active,
      traineesReserveCount: counts.reserve,
      traineesTotalCount: counts.total,
    },
  });
});

router.get(
  "/projects/:projectId/trainings/:trainingId/purge-preview",
  requirePermission("admin:purge-training", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    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 exists = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true },
    });
    if (!exists) return void res.status(404).json({ error: "Training not found." });
    const preview = await previewTrainingPurge(projectId, trainingId);
    res.json(preview);
  },
);

router.post(
  "/projects/:projectId/trainings/:trainingId/purge",
  requirePermission("admin:purge-training", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const parsed = z.object({ confirmTitle: z.string().min(1) }).safeParse(req.body);
    if (!parsed.success) {
      return void res.status(400).json({ error: "confirmTitle is required (exact training title)." });
    }
    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 training = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, title: true, trainingProviderId: true },
    });
    if (!training) return void res.status(404).json({ error: "Training not found." });
    if (parsed.data.confirmTitle.trim() !== training.title.trim()) {
      return void res.status(422).json({
        error: "Confirmation title does not match. Type the training title exactly.",
        expectedTitle: training.title,
      });
    }
    try {
      await assertProjectRegistrationOpen(projectId, training.trainingProviderId, "structure");
    } catch (e) {
      return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
    }
    const result = await executeTrainingPurge(projectId, trainingId, { actorUserId: req.auth!.userId });
    res.json(result);
  },
);

router.get(
  "/projects/:projectId/trainings/date-integrity/check",
  requirePermission("manage:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    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 trainingWhere = { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) };

    const [trainings, cohorts] = await Promise.all([
      prisma.training.findMany({
        where: trainingWhere,
        select: {
          id: true,
          title: true,
          trainingProviderId: true,
          startDate: true,
          endDate: true,
          timelineAnchorDate: true,
        },
        orderBy: { id: "desc" },
      }),
      prisma.trainingCohort.findMany({
        where: trainingWhere,
        select: {
          id: true,
          trainingId: true,
          code: true,
          name: true,
          startDate: true,
          endDate: true,
          timelineAnchorDate: true,
        },
        orderBy: { id: "desc" },
      }),
    ]);

    const trainingIssues = trainings
      .map((t) => {
        const issues: string[] = [];
        if (!isDateOnlyNoonUtc(t.startDate)) issues.push("startDate");
        if (!isDateOnlyNoonUtc(t.endDate)) issues.push("endDate");
        if (t.timelineAnchorDate && !isDateOnlyNoonUtc(t.timelineAnchorDate)) issues.push("timelineAnchorDate");
        if (!issues.length) return null;
        return {
          trainingId: asId(t.id),
          trainingTitle: t.title,
          trainingProviderId: asId(t.trainingProviderId),
          fields: issues,
          rawUtc: {
            startDate: t.startDate.toISOString(),
            endDate: t.endDate.toISOString(),
            timelineAnchorDate: t.timelineAnchorDate ? t.timelineAnchorDate.toISOString() : null,
          },
        };
      })
      .filter(Boolean);

    const cohortIssues = cohorts
      .map((c) => {
        const issues: string[] = [];
        if (!isDateOnlyNoonUtc(c.startDate)) issues.push("startDate");
        if (!isDateOnlyNoonUtc(c.endDate)) issues.push("endDate");
        if (c.timelineAnchorDate && !isDateOnlyNoonUtc(c.timelineAnchorDate)) issues.push("timelineAnchorDate");
        if (!issues.length) return null;
        return {
          cohortId: asId(c.id),
          trainingId: asId(c.trainingId),
          cohortCode: c.code,
          cohortName: c.name,
          fields: issues,
          rawUtc: {
            startDate: c.startDate.toISOString(),
            endDate: c.endDate.toISOString(),
            timelineAnchorDate: c.timelineAnchorDate ? c.timelineAnchorDate.toISOString() : null,
          },
        };
      })
      .filter(Boolean);

    res.json({
      checked: {
        trainings: trainings.length,
        cohorts: cohorts.length,
      },
      issues: {
        trainings: trainingIssues,
        cohorts: cohortIssues,
      },
      summary: {
        trainingIssueCount: trainingIssues.length,
        cohortIssueCount: cohortIssues.length,
        hasAnyIssue: trainingIssues.length > 0 || cohortIssues.length > 0,
      },
      note:
        "Date-only fields should be stored at 12:00:00.000Z. Legacy rows with other UTC times can cause cross-timezone day shifts in UI.",
    });
  },
);

router.post(
  "/projects/:projectId/trainings/date-integrity/normalize",
  requirePermission("manage:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const parsed = z.object({ dryRun: z.boolean().optional() }).safeParse(req.body ?? {});
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const dryRun = parsed.data.dryRun !== false;
    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 }); }
    try {
      await assertProjectRegistrationOpen(projectId, scope.providerId, "structure");
    } catch (e) {
      return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
    }
    const trainingWhere = { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) };

    const [trainings, cohorts] = await Promise.all([
      prisma.training.findMany({
        where: trainingWhere,
        select: {
          id: true,
          startDate: true,
          endDate: true,
          timelineAnchorDate: true,
        },
      }),
      prisma.trainingCohort.findMany({
        where: trainingWhere,
        select: {
          id: true,
          startDate: true,
          endDate: true,
          timelineAnchorDate: true,
        },
      }),
    ]);

    const trainingFixes = trainings
      .map((t) => {
        const nextStartDate = isDateOnlyNoonUtc(t.startDate) ? null : normalizeDateOnlyNoonUtc(t.startDate);
        const nextEndDate = isDateOnlyNoonUtc(t.endDate) ? null : normalizeDateOnlyNoonUtc(t.endDate);
        const nextAnchorDate = t.timelineAnchorDate && !isDateOnlyNoonUtc(t.timelineAnchorDate)
          ? normalizeDateOnlyNoonUtc(t.timelineAnchorDate)
          : null;
        if (!nextStartDate && !nextEndDate && !nextAnchorDate) return null;
        return {
          id: t.id,
          data: {
            ...(nextStartDate ? { startDate: nextStartDate } : {}),
            ...(nextEndDate ? { endDate: nextEndDate } : {}),
            ...(nextAnchorDate ? { timelineAnchorDate: nextAnchorDate } : {}),
          },
        };
      })
      .filter(Boolean) as Array<{ id: bigint; data: Prisma.TrainingUpdateInput }>;

    const cohortFixes = cohorts
      .map((c) => {
        const nextStartDate = isDateOnlyNoonUtc(c.startDate) ? null : normalizeDateOnlyNoonUtc(c.startDate);
        const nextEndDate = isDateOnlyNoonUtc(c.endDate) ? null : normalizeDateOnlyNoonUtc(c.endDate);
        const nextAnchorDate = c.timelineAnchorDate && !isDateOnlyNoonUtc(c.timelineAnchorDate)
          ? normalizeDateOnlyNoonUtc(c.timelineAnchorDate)
          : null;
        if (!nextStartDate && !nextEndDate && !nextAnchorDate) return null;
        return {
          id: c.id,
          data: {
            ...(nextStartDate ? { startDate: nextStartDate } : {}),
            ...(nextEndDate ? { endDate: nextEndDate } : {}),
            ...(nextAnchorDate ? { timelineAnchorDate: nextAnchorDate } : {}),
          },
        };
      })
      .filter(Boolean) as Array<{ id: bigint; data: Prisma.TrainingCohortUpdateInput }>;

    if (!dryRun) {
      await prisma.$transaction(async (tx) => {
        for (const f of trainingFixes) {
          await tx.training.update({ where: { id: f.id }, data: f.data });
        }
        for (const f of cohortFixes) {
          await tx.trainingCohort.update({ where: { id: f.id }, data: f.data });
        }
      });
      await audit({
        projectId,
        action: "training_date_integrity_normalized",
        sourceType: "training",
        sourceRef: "date-integrity-normalize",
        payloadRaw: JSON.stringify({
          dryRun: false,
          trainingRowsUpdated: trainingFixes.length,
          cohortRowsUpdated: cohortFixes.length,
          providerScoped: scope.providerId ? asId(scope.providerId) : null,
        }),
        actorUserId: req.auth!.userId,
      });
    }

    res.json({
      dryRun,
      checked: {
        trainings: trainings.length,
        cohorts: cohorts.length,
      },
      changed: {
        trainings: trainingFixes.length,
        cohorts: cohortFixes.length,
      },
      message: dryRun
        ? "Dry run complete. Re-run with dryRun=false to apply fixes."
        : "Date normalization complete.",
      policy:
        "Normalization rewrites flagged date-only fields to 12:00:00.000Z while preserving their UTC calendar date.",
    });
  },
);

router.get("/projects/:projectId/trainings/:trainingId/cohorts", requirePermission("view:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const scope = await resolveScope(projectId, req.auth!.userId);
  const training = await prisma.training.findFirst({
    where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: { id: true },
  });
  if (!training) return void res.status(404).json({ error: "Training not found." });
  const items = await prisma.trainingCohort.findMany({
    where: { projectId, trainingId },
    include: { location: { select: { id: true, name: true } } },
    orderBy: { id: "desc" },
  });
  const filtered = filterCohortsForScope(scope, items);
  res.json({
    items: filtered.map((c) => ({
      id: asId(c.id),
      trainingId: asId(c.trainingId),
      code: c.code,
      name: c.name,
      status: c.status,
      startDate: toDateOnlyYmd(c.startDate),
      endDate: toDateOnlyYmd(c.endDate),
      timelineAnchorDate: c.timelineAnchorDate ? c.timelineAnchorDate.toISOString().slice(0, 10) : null,
      sessionWeekdays: parseSessionWeekdays(c.sessionWeekdays),
      location: c.location ? { id: asId(c.location.id), name: c.location.name } : null,
    })),
  });
});

router.post("/projects/:projectId/trainings/:trainingId/cohorts", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const parsed = z.object({
    code: z.string().min(1).max(64),
    name: z.string().min(1).max(191),
    locationId: z.string().optional(),
    status: z.enum(["planned", "ongoing", "completed"]).default("planned"),
    startDate: z.string(),
    endDate: z.string(),
    timelineAnchorDate: z.string().optional(),
    sessionWeekdays: z.array(z.number().int().min(1).max(7)).optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const scope = await resolveScope(projectId, req.auth!.userId);
  const training = await prisma.training.findFirst({
    where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: { id: true, trainingProviderId: true, sessionWeekdays: true, startDate: true, endDate: true },
  });
  if (!training) return void res.status(404).json({ error: "Training not found." });
  try {
    await assertProjectRegistrationOpen(projectId, training.trainingProviderId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  try {
    await assertNoVerificationRunForProvider(projectId, training.trainingProviderId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const cohortStart = dateOnlyUtc(parsed.data.startDate);
  const cohortEnd = dateOnlyUtc(parsed.data.endDate);
  const trainingStart = dateOnlyUtc(training.startDate);
  const trainingEnd = dateOnlyUtc(training.endDate);
  if (cohortEnd < cohortStart) return void res.status(422).json({ error: "Cohort endDate must be on or after startDate." });
  if (cohortStart < trainingStart || cohortEnd > trainingEnd) {
    return void res.status(422).json({ error: "Cohort dates must stay inside the training date window." });
  }
  const cohortLocationId = parsed.data.locationId ? BigInt(parsed.data.locationId) : null;
  try {
    await assertCohortLocationInTrainingDeliverySites({ projectId, trainingId, locationId: cohortLocationId });
  } catch (e) {
    return void res.status((e as { status?: number }).status ?? 422).json({ error: (e as Error).message });
  }
  const created = await prisma.trainingCohort.create({
    data: {
      projectId,
      trainingId,
      trainingProviderId: training.trainingProviderId,
      code: parsed.data.code.trim(),
      name: parsed.data.name.trim(),
      locationId: parsed.data.locationId ? BigInt(parsed.data.locationId) : null,
      status: parsed.data.status,
      startDate: parseDateOnlyInput(parsed.data.startDate),
      endDate: parseDateOnlyInput(parsed.data.endDate),
      timelineAnchorDate: parsed.data.timelineAnchorDate ? new Date(parsed.data.timelineAnchorDate) : null,
      sessionWeekdays: parsed.data.sessionWeekdays ?? parseSessionWeekdays(training.sessionWeekdays),
    },
    select: {
      id: true,
      projectId: true,
      trainingProviderId: true,
      trainingId: true,
      startDate: true,
      endDate: true,
      timelineAnchorDate: true,
      sessionWeekdays: true,
    },
  });
  await ensureMainBatchForCohort(prisma, {
    id: created.id,
    projectId: created.projectId,
    trainingProviderId: created.trainingProviderId,
    trainingId: created.trainingId,
    startDate: created.startDate,
    endDate: created.endDate,
    timelineAnchorDate: created.timelineAnchorDate,
    sessionWeekdays: created.sessionWeekdays,
  });
  await audit({
    projectId,
    trainingProviderId: training.trainingProviderId,
    trainingId,
    cohortId: created.id,
    action: "cohort_created",
    sourceType: "cohort",
    sourceRef: created.id.toString(),
    payloadRaw: JSON.stringify(parsed.data),
    actorUserId: req.auth!.userId,
  });
  res.status(201).json({ item: { id: asId(created.id) } });
});

router.put("/projects/:projectId/trainings/:trainingId/cohorts/:cohortId", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const cohortId = BigInt(req.params.cohortId);
  const parsed = z.object({
    code: z.string().min(1).max(64),
    name: z.string().min(1).max(191),
    locationId: z.string().optional(),
    status: z.enum(["planned", "ongoing", "completed"]).default("planned"),
    startDate: z.string(),
    endDate: z.string(),
    timelineAnchorDate: z.string().optional(),
    sessionWeekdays: z.array(z.number().int().min(1).max(7)).optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const scope = await resolveScope(projectId, req.auth!.userId);
  const [exists, training] = await Promise.all([
    prisma.trainingCohort.findFirst({
      where: { id: cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true },
    }),
    prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, startDate: true, endDate: true, trainingProviderId: true },
    }),
  ]);
  if (!exists) return void res.status(404).json({ error: "Cohort not found." });
  if (!training) return void res.status(404).json({ error: "Training not found." });
  try {
    await assertProjectRegistrationOpen(projectId, training.trainingProviderId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const [trainingLevelBreakdowns, cohortBreakdowns] = await Promise.all([
    prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, cohortId: null, status: "approved" },
      select: { breakStartDate: true, breakEndDate: true },
    }),
    prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, cohortId, status: "approved" },
      select: { breakStartDate: true, breakEndDate: true },
    }),
  ]);
  const extensionDays = [...trainingLevelBreakdowns, ...cohortBreakdowns].reduce(
    (sum, b) => sum + diffDaysInclusive(b.breakStartDate, b.breakEndDate),
    0,
  );
  const cohortStart = dateOnlyUtc(parsed.data.startDate);
  const cohortEnd = dateOnlyUtc(parsed.data.endDate);
  const minStart = dateOnlyUtc(training.startDate);
  const maxEnd = dateOnlyUtc(training.endDate);
  maxEnd.setUTCDate(maxEnd.getUTCDate() + extensionDays);
  if (cohortEnd < cohortStart) return void res.status(422).json({ error: "Cohort endDate must be on or after startDate." });
  if (cohortStart < minStart || cohortEnd > maxEnd) {
    return void res.status(422).json({ error: "Cohort dates must stay inside training window plus approved breakdown extensions." });
  }
  const cohortLocationId = parsed.data.locationId ? BigInt(parsed.data.locationId) : null;
  try {
    await assertCohortLocationInTrainingDeliverySites({ projectId, trainingId, locationId: cohortLocationId });
  } catch (e) {
    return void res.status((e as { status?: number }).status ?? 422).json({ error: (e as Error).message });
  }
  const updated = await prisma.trainingCohort.update({
    where: { id: cohortId },
    data: {
      code: parsed.data.code.trim(),
      name: parsed.data.name.trim(),
      locationId: cohortLocationId,
      status: parsed.data.status,
      startDate: parseDateOnlyInput(parsed.data.startDate),
      endDate: parseDateOnlyInput(parsed.data.endDate),
      timelineAnchorDate: parsed.data.timelineAnchorDate ? new Date(parsed.data.timelineAnchorDate) : null,
      sessionWeekdays: parsed.data.sessionWeekdays ?? undefined,
    },
    select: { id: true },
  });
  await audit({
    projectId,
    trainingId,
    cohortId,
    action: "cohort_updated",
    sourceType: "cohort",
    sourceRef: cohortId.toString(),
    payloadRaw: JSON.stringify(parsed.data),
    actorUserId: req.auth!.userId,
  });
  res.json({ item: { id: asId(updated.id) } });
});

router.put(
  "/projects/:projectId/trainings/:trainingId/cohorts/:cohortId/actual-start",
  requirePermission("manage:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortId = BigInt(req.params.cohortId);
    const parsed = z
      .object({
        actualStartDate: z.string().optional().nullable(),
        sameAsPlanned: z.boolean().optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    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 }); }
    try {
      await guardStructureForTraining(projectId, trainingId);
    } catch (e) {
      return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
    }
    const cohort = await prisma.trainingCohort.findFirst({
      where: { id: cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, startDate: true, endDate: true, timelineAnchorDate: true },
    });
    if (!cohort) return void res.status(404).json({ error: "Cohort not found." });
    const soleBatches = await prisma.trainingBatch.findMany({
      where: { cohortId },
      select: { id: true },
      orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
    });
    if (soleBatches.length !== 1) {
      return void res.status(422).json({
        error:
          "This cohort has multiple delivery batches. Update actual start for each intake at PUT …/cohorts/:cohortId/batches/:batchId/actual-start.",
      });
    }
    const soleBatchId = soleBatches[0].id;

    const [batch, training] = await Promise.all([
      prisma.trainingBatch.findFirst({
        where: { id: soleBatchId, cohortId, trainingId, projectId },
        select: { id: true, startDate: true, endDate: true, timelineAnchorDate: true },
      }),
      prisma.training.findFirst({
        where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
        select: { id: true, startDate: true, endDate: true },
      }),
    ]);
    if (!batch) return void res.status(404).json({ error: "Delivery batch not found." });
    if (!training) return void res.status(404).json({ error: "Training not found." });
    const plannedStart = dateOnlyUtc(batch.startDate);
    const oldEffective = batch.timelineAnchorDate ? dateOnlyUtc(batch.timelineAnchorDate) : plannedStart;
    const requestedActual = parsed.data.sameAsPlanned ? null : (parsed.data.actualStartDate ? dateOnlyUtc(parsed.data.actualStartDate) : null);
    const newEffective = requestedActual ?? plannedStart;
    const blockingBreakdown = await prisma.trainingBreakdown.findFirst({
      where: {
        projectId,
        trainingId,
        status: "approved",
        breakStartDate: { lte: newEffective },
        breakEndDate: { gte: newEffective },
        OR: [
          { cohortId: null, batchId: null },
          { cohortId, batchId: null },
          { batchId: soleBatchId },
        ],
      },
      select: { id: true },
    });
    if (blockingBreakdown) {
      return void res.status(422).json({
        error:
          "Actual start date cannot be inside an approved breakdown window. Choose a date outside the approved pause range.",
      });
    }
    const deltaDays = diffDays(oldEffective, newEffective);
    const nextBatchEnd = dateOnlyUtc(batch.endDate);
    nextBatchEnd.setUTCDate(nextBatchEnd.getUTCDate() + deltaDays);
    const nextCohortEnd = dateOnlyUtc(cohort.endDate);
    nextCohortEnd.setUTCDate(nextCohortEnd.getUTCDate() + deltaDays);
    const nextTrainingEnd = dateOnlyUtc(training.endDate);
    nextTrainingEnd.setUTCDate(nextTrainingEnd.getUTCDate() + deltaDays);

    if (nextBatchEnd < plannedStart || nextCohortEnd < plannedStart) {
      return void res.status(422).json({ error: "Shift would move planned end dates before planned start date." });
    }
    const trainingPlannedStart = dateOnlyUtc(training.startDate);
    if (nextTrainingEnd < trainingPlannedStart) {
      return void res.status(422).json({ error: "Shift would move training end date before planned training start date." });
    }

    await prisma.$transaction([
      prisma.trainingBatch.update({
        where: { id: soleBatchId },
        data: {
          timelineAnchorDate: requestedActual ? new Date(requestedActual) : null,
          endDate: new Date(nextBatchEnd),
        },
        select: { id: true },
      }),
      prisma.trainingCohort.update({
        where: { id: cohortId },
        data: {
          timelineAnchorDate: requestedActual ? new Date(requestedActual) : null,
          endDate: new Date(nextCohortEnd),
        },
        select: { id: true, timelineAnchorDate: true, endDate: true },
      }),
      prisma.training.update({
        where: { id: trainingId },
        data: {
          endDate: new Date(nextTrainingEnd),
        },
        select: { id: true },
      }),
    ]);
    const updatedCohort = await prisma.trainingCohort.findUnique({
      where: { id: cohortId },
      select: { id: true, timelineAnchorDate: true, endDate: true },
    });
    if (!updatedCohort) return void res.status(500).json({ error: "Cohort disappeared during update." });

    await audit({
      projectId,
      trainingId,
      cohortId,
      batchId: soleBatchId,
      action: "cohort_actual_start_updated",
      sourceType: "cohort",
      sourceRef: cohortId.toString(),
      payloadRaw: JSON.stringify({
        previousEffectiveStart: oldEffective.toISOString().slice(0, 10),
        nextEffectiveStart: newEffective.toISOString().slice(0, 10),
        deltaDays,
        sameAsPlanned: !!parsed.data.sameAsPlanned,
        soleBatchId: soleBatchId.toString(),
        trainingEndShiftedByDays: deltaDays,
      }),
      actorUserId: req.auth!.userId,
    });
    res.json({
      item: {
        id: asId(updatedCohort.id),
        batchId: asId(soleBatchId),
        timelineAnchorDate: updatedCohort.timelineAnchorDate ? updatedCohort.timelineAnchorDate.toISOString().slice(0, 10) : null,
        endDate: updatedCohort.endDate.toISOString().slice(0, 10),
      },
    });
  },
);

router.delete("/projects/:projectId/trainings/:trainingId/cohorts/:cohortId", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const cohortId = BigInt(req.params.cohortId);
  const scope = await resolveScope(projectId, req.auth!.userId);
  try {
    await guardStructureForTraining(projectId, trainingId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const exists = await prisma.trainingCohort.findFirst({
    where: { id: cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: { id: true },
  });
  if (!exists) return void res.status(404).json({ error: "Cohort not found." });
  const cohortCount = await prisma.trainingCohort.count({ where: { projectId, trainingId } });
  if (cohortCount <= 1) {
    return void res.status(422).json({ error: "Cannot delete the last cohort for a training." });
  }
  const [traineeCount, outcomeCount, reportBatchCount, breakdownCount] = await Promise.all([
    prisma.trainee.count({ where: { projectId, trainingId, cohortId } }),
    prisma.traineeOutcome.count({ where: { projectId, trainingId, cohortId } }),
    prisma.outcomeReportBatch.count({ where: { projectId, trainingId, cohortId } }),
    prisma.trainingBreakdown.count({ where: { projectId, trainingId, cohortId } }),
  ]);
  if (traineeCount > 0 || outcomeCount > 0 || reportBatchCount > 0 || breakdownCount > 0) {
    return void res.status(422).json({
      error:
        "Cannot delete this cohort because it has linked records (trainees, outcome reports, outcome rows, or breakdowns).",
      details: { traineeCount, outcomeCount, reportBatchCount, breakdownCount },
    });
  }
  await prisma.trainingCohort.delete({ where: { id: cohortId } });
  await audit({
    projectId,
    trainingId,
    cohortId: null,
    action: "cohort_deleted",
    sourceType: "cohort",
    sourceRef: cohortId.toString(),
    actorUserId: req.auth!.userId,
  });
  res.json({ ok: true });
});

router.get("/projects/:projectId/trainings/:trainingId/cohorts/:cohortId/batches", requirePermission("view:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const cohortId = BigInt(req.params.cohortId);
  const scope = await resolveScope(projectId, req.auth!.userId);
  const cohort = await prisma.trainingCohort.findFirst({
    where: { id: cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: { id: true },
  });
  if (!cohort) return void res.status(404).json({ error: "Cohort not found." });
  try {
    assertDeliveryScope(scope, { trainingId, cohortId });
  } catch (e) {
    return void res.status((e as { status?: number }).status ?? 403).json({ error: (e as Error).message });
  }
  const rows = await prisma.trainingBatch.findMany({
    where: { projectId, trainingId, cohortId },
    orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
  });
  const filtered = filterBatchesForScope(scope, rows);
  res.json({
    items: filtered.map((b) => ({
      id: asId(b.id),
      cohortId: asId(b.cohortId),
      trainingId: asId(b.trainingId),
      code: b.code,
      name: b.name,
      campusLabel: b.campusLabel,
      sectionsCount: b.sectionsCount,
      sortOrder: b.sortOrder,
      status: b.status,
      startDate: toDateOnlyYmd(b.startDate),
      endDate: toDateOnlyYmd(b.endDate),
      timelineAnchorDate: b.timelineAnchorDate ? b.timelineAnchorDate.toISOString().slice(0, 10) : null,
      sessionWeekdays: parseSessionWeekdays(b.sessionWeekdays),
    })),
  });
});

router.post("/projects/:projectId/trainings/:trainingId/cohorts/:cohortId/batches", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const cohortId = BigInt(req.params.cohortId);
  const parsed = z.object({
    code: z.string().min(1).max(64),
    name: z.string().min(1).max(191),
    campusLabel: z.string().max(191).optional(),
    sectionsCount: z.number().int().nonnegative().optional(),
    sortOrder: z.number().int().nonnegative().optional(),
    status: z.enum(["planned", "ongoing", "completed"]).default("planned"),
    startDate: z.string(),
    endDate: z.string(),
    timelineAnchorDate: z.string().optional(),
    sessionWeekdays: z.array(z.number().int().min(1).max(7)).optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const scope = await resolveScope(projectId, req.auth!.userId);
  const cohort = await prisma.trainingCohort.findFirst({
    where: { id: cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: {
      projectId: true,
      trainingProviderId: true,
      trainingId: true,
      id: true,
      startDate: true,
      endDate: true,
      sessionWeekdays: true,
    },
  });
  if (!cohort) return void res.status(404).json({ error: "Cohort not found." });
  try {
    await assertProjectRegistrationOpen(projectId, cohort.trainingProviderId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  try {
    await assertNoVerificationRunForProvider(projectId, cohort.trainingProviderId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const training = await prisma.training.findFirst({
    where: { id: trainingId, projectId },
    select: { startDate: true, endDate: true },
  });
  if (!training) return void res.status(404).json({ error: "Training not found." });
  const cohortStart = dateOnlyUtc(cohort.startDate);
  const cohortEnd = dateOnlyUtc(cohort.endDate);
  const minStartTrain = dateOnlyUtc(training.startDate);
  const maxEndTrain = await trainingWindowMaxEndWithBreakdowns(prisma, {
    projectId,
    trainingId,
    trainingBaseEnd: training.endDate,
    cohortId,
    batchId: null,
  });
  const bStart = dateOnlyUtc(parsed.data.startDate);
  const bEnd = dateOnlyUtc(parsed.data.endDate);
  if (bEnd < bStart) return void res.status(422).json({ error: "Delivery batch endDate must be on or after startDate." });
  if (bStart < cohortStart || bEnd > cohortEnd || bStart < minStartTrain || bEnd > maxEndTrain) {
    return void res.status(422).json({ error: "Delivery batch dates must stay inside cohort and training envelopes (including approved breakdown extensions)." });
  }

  let sortOrder = parsed.data.sortOrder;
  if (sortOrder === undefined) {
    const agg = await prisma.trainingBatch.aggregate({
      where: { cohortId },
      _max: { sortOrder: true },
    });
    sortOrder = (agg._max.sortOrder ?? -1) + 1;
  }

  try {
    const created = await prisma.trainingBatch.create({
      data: {
        projectId: cohort.projectId,
        trainingProviderId: cohort.trainingProviderId,
        trainingId: cohort.trainingId,
        cohortId: cohort.id,
        code: parsed.data.code.trim(),
        name: parsed.data.name.trim(),
        campusLabel: parsed.data.campusLabel?.trim() || null,
        sectionsCount: parsed.data.sectionsCount ?? null,
        sortOrder,
        status: parsed.data.status,
        startDate: parseDateOnlyInput(parsed.data.startDate),
        endDate: parseDateOnlyInput(parsed.data.endDate),
        timelineAnchorDate: parsed.data.timelineAnchorDate ? parseDateOnlyInput(parsed.data.timelineAnchorDate) : null,
        sessionWeekdays:
          parsed.data.sessionWeekdays !== undefined
            ? (parsed.data.sessionWeekdays as never)
            : (cohort.sessionWeekdays as never) ?? undefined,
      },
      select: { id: true },
    });
    await audit({
      projectId,
      trainingProviderId: cohort.trainingProviderId,
      trainingId,
      cohortId: cohort.id,
      batchId: created.id,
      action: "training_batch_created",
      sourceType: "training_batch",
      sourceRef: created.id.toString(),
      payloadRaw: JSON.stringify(parsed.data),
      actorUserId: req.auth!.userId,
    });
    res.status(201).json({ item: { id: asId(created.id) } });
  } catch (e) {
    const msg = (e as Error).message ?? "";
    if (msg.includes("Unique constraint failed") || msg.includes("duplicate")) {
      return void res.status(422).json({ error: "A delivery batch with this code already exists in this cohort." });
    }
    throw e;
  }
});

router.put("/projects/:projectId/trainings/:trainingId/cohorts/:cohortId/batches/:batchId", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const cohortId = BigInt(req.params.cohortId);
  const batchId = BigInt(req.params.batchId);
  const parsed = z.object({
    code: z.string().min(1).max(64),
    name: z.string().min(1).max(191),
    campusLabel: z.string().max(191).optional(),
    sectionsCount: z.number().int().nonnegative().optional(),
    sortOrder: z.number().int().nonnegative().optional(),
    status: z.enum(["planned", "ongoing", "completed"]).default("planned"),
    startDate: z.string(),
    endDate: z.string(),
    timelineAnchorDate: z.string().optional(),
    sessionWeekdays: z.array(z.number().int().min(1).max(7)).optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const routeScope = await resolveScope(projectId, req.auth!.userId);
  try {
    await guardStructureForTraining(projectId, trainingId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const existing = await prisma.trainingBatch.findFirst({
    where: { id: batchId, cohortId, trainingId, projectId, ...(routeScope.providerId ? { trainingProviderId: routeScope.providerId } : {}) },
    select: {
      id: true,
      projectId: true,
      trainingProviderId: true,
      cohortId: true,
      trainingId: true,
      sessionWeekdays: true,
    },
  });
  if (!existing) return void res.status(404).json({ error: "Delivery batch not found." });
  const cohort = await prisma.trainingCohort.findFirst({
    where: { id: cohortId, trainingId, projectId, ...(routeScope.providerId ? { trainingProviderId: routeScope.providerId } : {}) },
    select: { startDate: true, endDate: true, sessionWeekdays: true },
  });
  const training = await prisma.training.findFirst({
    where: { id: trainingId, projectId, ...(routeScope.providerId ? { trainingProviderId: routeScope.providerId } : {}) },
    select: { startDate: true, endDate: true },
  });
  if (!cohort || !training) return void res.status(404).json({ error: "Training or cohort not found." });

  try {
    await assertNoVerificationRunForProvider(projectId, existing.trainingProviderId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }

  const cohortStart = dateOnlyUtc(cohort.startDate);
  const cohortEnd = dateOnlyUtc(cohort.endDate);
  const minStartTrain = dateOnlyUtc(training.startDate);
  const maxEndTrain = await trainingWindowMaxEndWithBreakdowns(prisma, {
    projectId,
    trainingId,
    trainingBaseEnd: training.endDate,
    cohortId,
    batchId,
  });
  const bStart = dateOnlyUtc(parsed.data.startDate);
  const bEnd = dateOnlyUtc(parsed.data.endDate);
  if (bEnd < bStart) return void res.status(422).json({ error: "Delivery batch endDate must be on or after startDate." });
  if (bStart < cohortStart || bEnd > cohortEnd || bStart < minStartTrain || bEnd > maxEndTrain) {
    return void res.status(422).json({ error: "Delivery batch dates must stay inside cohort and training envelopes (including approved breakdown extensions)." });
  }

  try {
    const updated = await prisma.trainingBatch.update({
      where: { id: batchId },
      data: {
        code: parsed.data.code.trim(),
        name: parsed.data.name.trim(),
        campusLabel: parsed.data.campusLabel?.trim() || null,
        sectionsCount: parsed.data.sectionsCount ?? null,
        sortOrder: parsed.data.sortOrder ?? undefined,
        status: parsed.data.status,
        startDate: parseDateOnlyInput(parsed.data.startDate),
        endDate: parseDateOnlyInput(parsed.data.endDate),
        timelineAnchorDate: parsed.data.timelineAnchorDate ? parseDateOnlyInput(parsed.data.timelineAnchorDate) : null,
        sessionWeekdays:
          parsed.data.sessionWeekdays !== undefined
            ? (parsed.data.sessionWeekdays as never)
            : existing.sessionWeekdays ?? undefined,
      },
      select: { id: true },
    });
    await audit({
      projectId,
      trainingProviderId: existing.trainingProviderId,
      trainingId,
      cohortId,
      batchId,
      action: "training_batch_updated",
      sourceType: "training_batch",
      sourceRef: batchId.toString(),
      payloadRaw: JSON.stringify(parsed.data),
      actorUserId: req.auth!.userId,
    });
    res.json({ item: { id: asId(updated.id) } });
  } catch (e) {
    const msg = (e as Error).message ?? "";
    if (msg.includes("Unique constraint failed") || msg.includes("duplicate")) {
      return void res.status(422).json({ error: "A delivery batch with this code already exists in this cohort." });
    }
    throw e;
  }
});

router.put(
  "/projects/:projectId/trainings/:trainingId/cohorts/:cohortId/batches/:batchId/actual-start",
  requirePermission("manage:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const cohortId = BigInt(req.params.cohortId);
    const batchId = BigInt(req.params.batchId);
    const parsed = z
      .object({
        actualStartDate: z.string().optional().nullable(),
        sameAsPlanned: z.boolean().optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    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 }); }
    try {
      await guardStructureForTraining(projectId, trainingId);
    } catch (e) {
      return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
    }

    const [batch, cohort, training] = await Promise.all([
      prisma.trainingBatch.findFirst({
        where: { id: batchId, cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
        select: { id: true, startDate: true, endDate: true, timelineAnchorDate: true },
      }),
      prisma.trainingCohort.findFirst({
        where: { id: cohortId, trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
        select: { id: true, startDate: true, endDate: true, timelineAnchorDate: true },
      }),
      prisma.training.findFirst({
        where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
        select: { id: true, startDate: true, endDate: true },
      }),
    ]);
    if (!batch) return void res.status(404).json({ error: "Delivery batch not found." });
    if (!cohort) return void res.status(404).json({ error: "Cohort not found." });
    if (!training) return void res.status(404).json({ error: "Training not found." });

    const plannedStart = dateOnlyUtc(batch.startDate);
    const oldEffective = batch.timelineAnchorDate ? dateOnlyUtc(batch.timelineAnchorDate) : plannedStart;
    const requestedActual = parsed.data.sameAsPlanned ? null : (parsed.data.actualStartDate ? dateOnlyUtc(parsed.data.actualStartDate) : null);
    const newEffective = requestedActual ?? plannedStart;

    const blockingBreakdown = await prisma.trainingBreakdown.findFirst({
      where: {
        projectId,
        trainingId,
        status: "approved",
        breakStartDate: { lte: newEffective },
        breakEndDate: { gte: newEffective },
        OR: [
          { cohortId: null, batchId: null },
          { cohortId, batchId: null },
          { batchId },
        ],
      },
      select: { id: true },
    });
    if (blockingBreakdown) {
      return void res.status(422).json({
        error:
          "Actual start date cannot be inside an approved breakdown window. Choose a date outside the approved pause range.",
      });
    }
    const deltaDays = diffDays(oldEffective, newEffective);
    const nextBatchEnd = dateOnlyUtc(batch.endDate);
    nextBatchEnd.setUTCDate(nextBatchEnd.getUTCDate() + deltaDays);

    if (nextBatchEnd < plannedStart) {
      return void res.status(422).json({ error: "Shift would move planned end date before planned start date." });
    }
    const siblingCount = await prisma.trainingBatch.count({ where: { cohortId } });
    const shouldWriteCohortAnchor = siblingCount <= 1;

    await prisma.trainingBatch.update({
      where: { id: batchId },
      data: {
        timelineAnchorDate: requestedActual ? new Date(requestedActual) : null,
        endDate: new Date(nextBatchEnd),
      },
      select: { id: true },
    });

    // Cohort end should reflect the max end across its batches (prevents double-extension).
    const cohortBatchEnds = await prisma.trainingBatch.findMany({
      where: { projectId, trainingId, cohortId },
      select: { endDate: true },
    });
    const maxBatchEnd = cohortBatchEnds.reduce<Date>((max, r) => (r.endDate.getTime() > max.getTime() ? r.endDate : max), nextBatchEnd);
    await prisma.trainingCohort.update({
      where: { id: cohortId },
      data: {
        endDate: new Date(maxBatchEnd),
        ...(shouldWriteCohortAnchor ? { timelineAnchorDate: requestedActual ? new Date(requestedActual) : null } : {}),
      },
      select: { id: true },
    });

    // Training end should reflect the max end across cohorts.
    const cohortEnds = await prisma.trainingCohort.findMany({
      where: { projectId, trainingId },
      select: { endDate: true },
    });
    const maxCohortEnd = cohortEnds.reduce<Date>((max, r) => (r.endDate.getTime() > max.getTime() ? r.endDate : max), maxBatchEnd);
    const trainingPlannedStart = dateOnlyUtc(training.startDate);
    if (dateOnlyUtc(maxCohortEnd) < trainingPlannedStart) {
      return void res.status(422).json({ error: "Shift would move training end date before planned training start date." });
    }
    await prisma.training.update({
      where: { id: trainingId },
      data: { endDate: new Date(maxCohortEnd) },
      select: { id: true },
    });

    const refreshed = await prisma.trainingBatch.findUnique({
      where: { id: batchId },
      select: { timelineAnchorDate: true, endDate: true },
    });

    await audit({
      projectId,
      trainingId,
      cohortId,
      batchId,
      action: "training_batch_actual_start_updated",
      sourceType: "training_batch",
      sourceRef: batchId.toString(),
      payloadRaw: JSON.stringify({
        previousEffectiveStart: oldEffective.toISOString().slice(0, 10),
        nextEffectiveStart: newEffective.toISOString().slice(0, 10),
        deltaDays,
        propagateToTraining: true,
      }),
      actorUserId: req.auth!.userId,
    });
    res.json({
      item: {
        id: asId(batchId),
        timelineAnchorDate: refreshed?.timelineAnchorDate ? refreshed.timelineAnchorDate.toISOString().slice(0, 10) : null,
        endDate: refreshed?.endDate ? refreshed.endDate.toISOString().slice(0, 10) : null,
      },
    });
  },
);

router.delete("/projects/:projectId/trainings/:trainingId/cohorts/:cohortId/batches/:batchId", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const cohortId = BigInt(req.params.cohortId);
  const batchId = BigInt(req.params.batchId);
  const routeScopeDel = await resolveScope(projectId, req.auth!.userId);
  const batch = await prisma.trainingBatch.findFirst({
    where: { id: batchId, cohortId, trainingId, projectId, ...(routeScopeDel.providerId ? { trainingProviderId: routeScopeDel.providerId } : {}) },
    select: { id: true, trainingProviderId: true },
  });
  if (!batch) return void res.status(404).json({ error: "Delivery batch not found." });
  try {
    await assertProjectRegistrationOpen(projectId, batch.trainingProviderId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const [traineeCount, outcomeCount, reportBatchCount, breakdownCount] = await Promise.all([
    prisma.trainee.count({ where: { batchId } }),
    prisma.traineeOutcome.count({ where: { batchId } }),
    prisma.outcomeReportBatch.count({ where: { batchId } }),
    prisma.trainingBreakdown.count({ where: { batchId } }),
  ]);
  if (traineeCount > 0 || outcomeCount > 0 || reportBatchCount > 0 || breakdownCount > 0) {
    return void res.status(422).json({
      error:
        "Cannot delete this delivery batch because it has linked records (trainees, outcome reports, outcome rows, or breakdowns).",
      details: { traineeCount, outcomeCount, reportBatchCount, breakdownCount },
    });
  }
  const batchCount = await prisma.trainingBatch.count({ where: { cohortId } });
  if (batchCount <= 1) {
    return void res.status(422).json({ error: "Each cohort must keep at least one delivery batch." });
  }
  try {
    await assertNoVerificationRunForProvider(projectId, batch.trainingProviderId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  await prisma.trainingBatch.delete({ where: { id: batchId } });
  await audit({
    projectId,
    trainingId,
    cohortId,
    batchId: null,
    action: "training_batch_deleted",
    sourceType: "training_batch",
    sourceRef: batchId.toString(),
    actorUserId: req.auth!.userId,
  });
  res.json({ ok: true });
});

router.post("/projects/:projectId/trainings", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const parsed = z.object({
    trainingProviderId: z.string().optional(),
    trainingProgramId: z.string().optional(),
    title: z.string().min(1),
    trainingType: z.enum(["Basic", "Intermediate", "Advanced"]),
    startDate: z.string(),
    endDate: z.string(),
    timelineAnchorDate: z.string().optional(),
    locationId: z.string().optional(),
    deliveryLocationIds: z.array(z.string().regex(/^\d+$/)).optional(),
    trainingDurationId: z.string().optional(),
    intakeTarget: z.number().int().positive().optional().nullable(),
    notes: z.string().optional(),
    status: z.enum(["planned", "ongoing", "completed"]).default("planned"),
    sessionWeekdays: z.array(z.number().int().min(1).max(7)).optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  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 deliveryIds = normalizeDeliveryLocationIdsInput({
    deliveryLocationIds: parsed.data.deliveryLocationIds,
    locationId: parsed.data.locationId,
  });
  if (deliveryIds.length === 0) {
    return void res.status(400).json({ error: "Select at least one delivery location for this training." });
  }
  const requestedProviderIdRaw = parsed.data.trainingProviderId?.trim();
  if (requestedProviderIdRaw && !/^\d+$/.test(requestedProviderIdRaw)) {
    return void res.status(400).json({ error: "trainingProviderId must be a numeric id." });
  }
  const requestedProviderId = requestedProviderIdRaw ? BigInt(requestedProviderIdRaw) : null;
  const requestedProgramIdRaw = parsed.data.trainingProgramId?.trim();
  if (requestedProgramIdRaw && !/^\d+$/.test(requestedProgramIdRaw)) {
    return void res.status(400).json({ error: "trainingProgramId must be a numeric id." });
  }
  if (scope.providerId && requestedProviderId && scope.providerId !== requestedProviderId) {
    return void res.status(403).json({ error: "TP users can only create trainings under their own provider." });
  }
  const effectiveProviderId = scope.providerId ?? requestedProviderId;
  if (!effectiveProviderId) {
    return void res.status(400).json({ error: "trainingProviderId is required." });
  }
  try {
    await assertProjectRegistrationOpen(projectId, effectiveProviderId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  try {
    await assertNoVerificationRunForProvider(projectId, effectiveProviderId);
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const requestedProgramId = requestedProgramIdRaw ? BigInt(requestedProgramIdRaw) : null;
  let effectiveProgramId = requestedProgramId;
  if (!effectiveProgramId) {
    const upsertedProgram = await prisma.trainingProgram.upsert({
      where: {
        projectId_trainingProviderId_name: {
          projectId,
          trainingProviderId: effectiveProviderId,
          name: parsed.data.title.trim(),
        },
      },
      create: {
        projectId,
        trainingProviderId: effectiveProviderId,
        name: parsed.data.title.trim(),
        trainingType: parsed.data.trainingType,
      },
      update: {},
      select: { id: true },
    });
    effectiveProgramId = upsertedProgram.id;
  }
  const created = await prisma.training.create({
    data: {
      projectId,
      trainingProviderId: effectiveProviderId,
      trainingProgramId: effectiveProgramId,
      title: parsed.data.title.trim(),
      trainingType: parsed.data.trainingType,
      startDate: parseDateOnlyInput(parsed.data.startDate),
      endDate: parseDateOnlyInput(parsed.data.endDate),
      timelineAnchorDate: parsed.data.timelineAnchorDate ? new Date(parsed.data.timelineAnchorDate) : null,
      locationId: BigInt(deliveryIds[0]!),
      deliveryLocationIds: deliveryIds as never,
      trainingDurationId: parsed.data.trainingDurationId ? BigInt(parsed.data.trainingDurationId) : null,
      intakeTarget: parsed.data.intakeTarget ?? null,
      notes: parsed.data.notes?.trim() || null,
      status: parsed.data.status,
      sessionWeekdays: parsed.data.sessionWeekdays ?? [1, 2, 3, 4, 5],
    },
  });
  const deliveryLocationBigInts = deliveryIds.map((id) => BigInt(id));
  if (deliveryLocationBigInts.length === 1) {
    await ensureMainCohortAndBatchForTraining(prisma, {
      projectId,
      trainingProviderId: effectiveProviderId,
      trainingId: created.id,
      locationId: deliveryLocationBigInts[0]!,
      startDate: created.startDate,
      endDate: created.endDate,
      timelineAnchorDate: created.timelineAnchorDate,
      sessionWeekdays: created.sessionWeekdays,
    });
  } else {
    await ensureCohortsForDeliverySites(prisma, {
      projectId,
      trainingProviderId: effectiveProviderId,
      trainingId: created.id,
      deliveryLocationIds: deliveryLocationBigInts,
      startDate: created.startDate,
      endDate: created.endDate,
      timelineAnchorDate: created.timelineAnchorDate,
      sessionWeekdays: created.sessionWeekdays,
    });
  }
  await audit({
    projectId,
    trainingProviderId: effectiveProviderId,
    trainingId: created.id,
    action: "training_created",
    sourceType: "training",
    sourceRef: created.id.toString(),
    payloadRaw: JSON.stringify(parsed.data),
    actorUserId: req.auth!.userId,
  });
  res.json({ item: { id: asId(created.id) } });
});

router.put("/projects/:projectId/trainings/:trainingId", requirePermission("manage:trainings", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const trainingId = BigInt(req.params.trainingId);
  const parsed = z.object({
    trainingProgramId: z.string().optional(),
    title: z.string().min(1),
    trainingType: z.enum(["Basic", "Intermediate", "Advanced"]),
    startDate: z.string(),
    endDate: z.string(),
    timelineAnchorDate: z.string().optional(),
    locationId: z.string().optional(),
    deliveryLocationIds: z.array(z.string().regex(/^\d+$/)).optional(),
    trainingDurationId: z.string().optional(),
    intakeTarget: z.number().int().positive().optional().nullable(),
    notes: z.string().optional(),
    status: z.enum(["planned", "ongoing", "completed"]).default("planned"),
    sessionWeekdays: z.array(z.number().int().min(1).max(7)).optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  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 existing = await prisma.training.findFirst({
    where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: { id: true, trainingProviderId: true },
  });
  if (!existing) return void res.status(404).json({ error: "Training not found." });
  try {
    await assertProjectRegistrationOpen(projectId, existing.trainingProviderId, "structure");
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  if (dateOnlyUtc(parsed.data.endDate) < dateOnlyUtc(parsed.data.startDate)) {
    return void res.status(422).json({ error: "Training endDate must be on or after startDate." });
  }
  const deliveryIds =
    parsed.data.deliveryLocationIds !== undefined || parsed.data.locationId !== undefined
      ? normalizeDeliveryLocationIdsInput({
          deliveryLocationIds: parsed.data.deliveryLocationIds,
          locationId: parsed.data.locationId,
        })
      : null;
  if (deliveryIds !== null && deliveryIds.length === 0) {
    return void res.status(400).json({ error: "Select at least one delivery location for this training." });
  }
  const updated = await prisma.training.update({
    where: { id: trainingId },
    data: {
      trainingProgramId: parsed.data.trainingProgramId && /^\d+$/.test(parsed.data.trainingProgramId) ? BigInt(parsed.data.trainingProgramId) : null,
      title: parsed.data.title.trim(),
      trainingType: parsed.data.trainingType,
      startDate: parseDateOnlyInput(parsed.data.startDate),
      endDate: parseDateOnlyInput(parsed.data.endDate),
      timelineAnchorDate: parsed.data.timelineAnchorDate ? new Date(parsed.data.timelineAnchorDate) : null,
      ...(deliveryIds !== null
        ? { locationId: BigInt(deliveryIds[0]!), deliveryLocationIds: deliveryIds as never }
        : parsed.data.locationId
          ? { locationId: BigInt(parsed.data.locationId) }
          : {}),
      trainingDurationId: parsed.data.trainingDurationId ? BigInt(parsed.data.trainingDurationId) : null,
      intakeTarget: parsed.data.intakeTarget === undefined ? undefined : parsed.data.intakeTarget,
      notes: parsed.data.notes?.trim() || null,
      status: parsed.data.status,
      sessionWeekdays: parsed.data.sessionWeekdays ?? [1, 2, 3, 4, 5],
    },
    select: { id: true },
  });
  await audit({
    projectId,
    trainingId,
    action: "training_updated",
    sourceType: "training",
    sourceRef: trainingId.toString(),
    payloadRaw: JSON.stringify(parsed.data),
    actorUserId: req.auth!.userId,
  });
  res.json({ item: { id: asId(updated.id) } });
});

router.put(
  "/projects/:projectId/trainings/:trainingId/actual-start",
  requirePermission("manage:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const parsed = z
      .object({
        actualStartDate: z.string().optional().nullable(),
        sameAsPlanned: z.boolean().optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    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 }); }
    try {
      await guardStructureForTraining(projectId, trainingId);
    } catch (e) {
      return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
    }
    const training = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, startDate: true, endDate: true, timelineAnchorDate: true },
    });
    if (!training) return void res.status(404).json({ error: "Training not found." });
    const cohortCountForActual = await prisma.trainingCohort.count({ where: { projectId, trainingId } });
    if (cohortCountForActual > 1) {
      return void res.status(422).json({
        error: "This training has multiple cohorts. Set actual start per cohort (or per delivery batch where applicable).",
      });
    }
    const plannedStart = dateOnlyUtc(training.startDate);
    const oldEffective = training.timelineAnchorDate ? dateOnlyUtc(training.timelineAnchorDate) : plannedStart;
    const requestedActual = parsed.data.sameAsPlanned ? null : (parsed.data.actualStartDate ? dateOnlyUtc(parsed.data.actualStartDate) : null);
    const newEffective = requestedActual ?? plannedStart;
    const blockingBreakdown = await prisma.trainingBreakdown.findFirst({
      where: {
        projectId,
        trainingId,
        status: "approved",
        cohortId: null,
        batchId: null,
        breakStartDate: { lte: newEffective },
        breakEndDate: { gte: newEffective },
      },
      select: { id: true, breakStartDate: true, breakEndDate: true },
    });
    if (blockingBreakdown) {
      return void res.status(422).json({
        error:
          "Actual start date cannot be inside an approved breakdown window. Choose a date outside the approved pause range.",
      });
    }
    const deltaDays = diffDays(oldEffective, newEffective);
    const nextEnd = dateOnlyUtc(training.endDate);
    nextEnd.setUTCDate(nextEnd.getUTCDate() + deltaDays);
    if (nextEnd < plannedStart) {
      return void res.status(422).json({ error: "Shift would move training end date before planned start date." });
    }
    const updated = await prisma.training.update({
      where: { id: trainingId },
      data: {
        timelineAnchorDate: requestedActual ? new Date(requestedActual) : null,
        endDate: new Date(nextEnd),
      },
      select: { id: true, timelineAnchorDate: true, endDate: true },
    });
    await audit({
      projectId,
      trainingId,
      action: "training_actual_start_updated",
      sourceType: "training",
      sourceRef: trainingId.toString(),
      payloadRaw: JSON.stringify({
        previousEffectiveStart: oldEffective.toISOString().slice(0, 10),
        nextEffectiveStart: newEffective.toISOString().slice(0, 10),
        deltaDays,
        sameAsPlanned: !!parsed.data.sameAsPlanned,
      }),
      actorUserId: req.auth!.userId,
    });
    res.json({
      item: {
        id: asId(updated.id),
        timelineAnchorDate: updated.timelineAnchorDate ? updated.timelineAnchorDate.toISOString().slice(0, 10) : null,
        endDate: updated.endDate.toISOString().slice(0, 10),
      },
    });
  },
);

router.get("/projects/:projectId/trainees", requirePermission("view:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  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 trainingProviderId =
    typeof req.query.trainingProviderId === "string" && /^\d+$/.test(req.query.trainingProviderId)
      ? BigInt(req.query.trainingProviderId)
      : undefined;
  const trainingId = typeof req.query.trainingId === "string" ? BigInt(req.query.trainingId) : undefined;
  const cohortId = typeof req.query.cohortId === "string" ? BigInt(req.query.cohortId) : undefined;
  const batchId = typeof req.query.batchId === "string" ? BigInt(req.query.batchId) : undefined;
  const rosterRole = typeof req.query.rosterRole === "string" && req.query.rosterRole.trim() ? req.query.rosterRole.trim() : undefined;
  const q = typeof req.query.q === "string" ? req.query.q.trim() : "";
  const eligibility = typeof req.query.eligibility === "string" ? req.query.eligibility.trim().toLowerCase() : "all";
  const page = Math.max(1, Number.parseInt(String(req.query.page ?? "1"), 10) || 1);
  const pageSize = Math.min(100, Math.max(1, Number.parseInt(String(req.query.pageSize ?? "25"), 10) || 25));
  const skip = (page - 1) * pageSize;

  if (scope.providerId && trainingProviderId && scope.providerId !== trainingProviderId) {
    return void res.status(403).json({ error: "TP users can only view trainees under their own provider." });
  }

  const deliveryScopeFilter = traineeDeliveryScopeWhere(scope);
  const scopeFilters: Prisma.TraineeWhereInput = {
    projectId,
    ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}),
    ...(trainingProviderId ? { trainingProviderId } : {}),
    ...(trainingId ? { trainingId } : {}),
    ...(cohortId ? { cohortId } : {}),
    ...(batchId ? { batchId } : {}),
    ...(rosterRole ? { rosterRole } : {}),
    ...(deliveryScopeFilter ?? {}),
  };

  if (cohortId) {
    try {
      assertDeliveryScope(scope, { trainingId, cohortId, batchId });
    } catch (e) {
      return void res.status((e as { status?: number }).status ?? 403).json({ error: (e as Error).message });
    }
  } else if (batchId) {
    try {
      assertDeliveryScope(scope, { trainingId, batchId });
    } catch (e) {
      return void res.status((e as { status?: number }).status ?? 403).json({ error: (e as Error).message });
    }
  }

  const andParts: Prisma.TraineeWhereInput[] = [scopeFilters];
  if (q) {
    andParts.push({ OR: buildTraineeSearchOrFilters(q) });
  }
  if (eligibility === "eligible") andParts.push(eligibilityProtocolWhere());
  else if (eligibility === "ineligible") andParts.push({ NOT: eligibilityProtocolWhere() });

  const listWhere: Prisma.TraineeWhereInput = { AND: andParts };
  const summaryAndParts: Prisma.TraineeWhereInput[] = [scopeFilters];
  if (q) {
    summaryAndParts.push({ OR: buildTraineeSearchOrFilters(q, { includePhoneAlternative: false }) });
  }
  const activeSummaryWhereClean: Prisma.TraineeWhereInput = {
    AND: [...summaryAndParts, { rosterRole: trackedRosterRoleFilter() }],
  };

  const [total, rows, totalAll, trackedTotal, eligibleActive, femaleActive] = await Promise.all([
    prisma.trainee.count({ where: listWhere }),
    prisma.trainee.findMany({
      where: listWhere,
      include: {
        training: { select: { title: true, location: { select: { name: true } } } },
        trainingProvider: true,
        trainingDuration: { select: { months: true } },
        cohort: { select: { id: true, code: true, name: true, location: { select: { name: true } } } },
        batch: { select: { id: true, code: true, name: true } },
      },
      orderBy: { id: "desc" },
      skip,
      take: pageSize,
    }),
    prisma.trainee.count({ where: { AND: summaryAndParts } }),
    prisma.trainee.count({ where: activeSummaryWhereClean }),
    prisma.trainee.count({ where: { AND: [...summaryAndParts, { rosterRole: trackedRosterRoleFilter() }, eligibilityProtocolWhere()] } }),
    prisma.trainee.count({ where: { AND: [...summaryAndParts, { rosterRole: trackedRosterRoleFilter() }, { sex: "Female" }] } }),
  ]);

  const items = rows;
  res.json({
    total,
    page,
    pageSize,
    summary: {
      totalAll,
      trackedTotal,
      registeredTotal: totalAll,
      /** @deprecated Use totalAll */
      activeTotal: trackedTotal,
      eligibleActive,
      eligibilityRate: toPercent(eligibleActive, trackedTotal),
      femaleRate: toPercent(femaleActive, trackedTotal),
    },
    items: items.map((t) => ({
    id: asId(t.id),
    traineeUniqueId: t.traineeUniqueId,
    externalBeneficiaryId: t.externalBeneficiaryId,
    firstName: t.firstName,
    fatherName: t.fatherName,
    grandfatherName: t.grandfatherName,
    sex: t.sex,
    ageYears: t.ageYears,
    dateOfBirthEtCalendar: t.dateOfBirthEtCalendar,
    phonePrimary: t.phonePrimary,
    phoneAlternative: t.phoneAlternative,
    email: t.email,
    kebele: t.kebele,
    woreda: t.woreda,
    subCity: t.subCity,
    region: t.region,
    emergencyContactName: t.emergencyContactName,
    emergencyContactPhone: t.emergencyContactPhone,
    highestEducation: t.highestEducation,
    previouslyParticipated: t.previouslyParticipated,
    priorTrainingType: t.priorTrainingType,
    priorCompleted: t.priorCompleted,
    priorYearCompleted: t.priorYearCompleted,
    employmentStatus: t.employmentStatus,
    incomeSufficient: t.incomeSufficient,
    skillUsage: t.skillUsage,
    postTrainingEmploymentPlanType: t.postTrainingEmploymentPlanType,
    postTrainingEmploymentPlanOtherText: t.postTrainingEmploymentPlanOtherText,
    disabilityFlag: t.disabilityFlag,
    disabilityType: t.disabilityType,
    disabilityOtherText: t.disabilityOtherText,
    idpFlag: t.idpFlag,
    returneeFlag: t.returneeFlag,
    lowIncomeFlag: t.lowIncomeFlag,
    inclusionNoneOfAbove: t.inclusionNoneOfAbove,
    inclusionPreferNotToSay: t.inclusionPreferNotToSay,
    consentAccuracy: t.consentAccuracy,
    consentFollowupSurveys: t.consentFollowupSurveys,
    consentContactVerify: t.consentContactVerify,
    consentImageUse: t.consentImageUse,
    trainingType: t.trainingType,
    trainingLocation: t.trainingLocation,
    trainingDurationMonths: t.trainingDuration?.months ?? null,
    dateOfFormCompletion: t.dateOfFormCompletion ? t.dateOfFormCompletion.toISOString().slice(0, 10) : null,
    trainingId: t.trainingId ? asId(t.trainingId) : null,
    cohortId: t.cohortId ? asId(t.cohortId) : null,
    batchId: t.batchId ? asId(t.batchId) : null,
    cohort: t.cohort
      ? {
          id: asId(t.cohort.id),
          code: t.cohort.code,
          name: t.cohort.name,
          locationName: t.cohort.location?.name ?? null,
        }
      : null,
    deliveryBatch: t.batch ? { id: asId(t.batch.id), code: t.batch.code, name: t.batch.name } : null,
    trainingProviderId: asId(t.trainingProviderId),
    trainingTitle: t.training?.title ?? null,
    trainingDefaultLocationName: t.training?.location?.name ?? null,
    providerName: t.trainingProvider.name,
    rosterRole: t.rosterRole,
    attendanceEligibleFrom: t.attendanceEligibleFrom ? t.attendanceEligibleFrom.toISOString().slice(0, 10) : null,
    replacesTraineeId: t.replacesTraineeId ? asId(t.replacesTraineeId) : null,
    createdAt: t.createdAt.toISOString(),
  })),
  });
});

/** Lightweight aggregates for dashboard charts (no full trainee list). */
router.get(
  "/projects/:projectId/trainees/roster-insights",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    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 tpFilter =
      typeof req.query.trainingProviderId === "string" && req.query.trainingProviderId.trim()
        ? BigInt(req.query.trainingProviderId)
        : scope.providerId ?? undefined;
    const item = await computeRosterInsights(projectId, tpFilter);
    res.json({ item });
  },
);

/** Check whether a phone is already used in this project (canonical +251 / 09 / 9… formats). */
router.get(
  "/projects/:projectId/trainees/phone-check",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    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 phoneRaw = typeof req.query.phone === "string" ? req.query.phone.trim() : "";
    const key = canonicalPhoneKey(phoneRaw);
    if (!key) return void res.json({ canonical: null, exists: false, match: null });
    const conflict = await findConflictingTraineeByPhone({ projectId, phonePrimary: phoneRaw });
    res.json({
      canonical: key,
      exists: Boolean(conflict),
      match: conflict
        ? {
            id: asId(conflict.id),
            firstName: conflict.firstName,
            phonePrimary: conflict.phonePrimary,
          }
        : null,
    });
  },
);

router.post("/projects/:projectId/trainees", requirePermission("create:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const parsed = z.object({
    trainingProviderId: z.string(),
    trainingId: z.string().optional(),
    cohortId: z.string().optional(),
    batchId: z.string().regex(/^\d+$/).optional(),
    deliveryBatchCode: z.string().min(1).max(64).optional(),
    locationId: z.string().optional(),
    trainingDurationId: z.string().optional(),
    trainingType: z.string().optional(),
    trainingLocation: z.string().optional(),
    dateOfFormCompletion: z.string().optional(),
    firstName: z.string().min(1),
    fatherName: z.string().optional(),
    grandfatherName: z.string().optional(),
    sex: z.string().min(1),
    ageYears: z.number().int().optional(),
    dateOfBirthEtCalendar: z.string().optional(),
    phonePrimary: z.string().optional(),
    phoneAlternative: z.string().optional(),
    email: optionalEmailField,
    kebele: z.string().optional(),
    woreda: z.string().optional(),
    subCity: z.string().optional(),
    region: z.string().optional(),
    emergencyContactName: z.string().optional(),
    emergencyContactPhone: z.string().optional(),
    highestEducation: z.string().optional(),
    previouslyParticipated: z.boolean().optional(),
    priorTrainingType: z.string().optional(),
    priorCompleted: z.boolean().optional(),
    priorYearCompleted: z.number().int().optional(),
    employmentStatus: z.string().optional(),
    incomeSufficient: z.boolean().optional(),
    skillUsage: z.string().optional(),
    postTrainingEmploymentPlanType: z.string().optional(),
    postTrainingEmploymentPlanOtherText: z.string().optional(),
    disabilityFlag: z.boolean().optional(),
    disabilityType: z.string().optional(),
    disabilityOtherText: z.string().optional(),
    idpFlag: z.boolean().optional(),
    returneeFlag: z.boolean().optional(),
    lowIncomeFlag: z.boolean().optional(),
    inclusionNoneOfAbove: z.boolean().optional(),
    inclusionPreferNotToSay: z.boolean().optional(),
    consentAccuracy: z.boolean().optional(),
    consentFollowupSurveys: z.boolean().optional(),
    consentContactVerify: z.boolean().optional(),
    consentImageUse: z.boolean().optional(),
    externalBeneficiaryId: z.string().optional(),
    rawPayload: z.record(z.any()).optional(),
    rosterRole: z.string().optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const requestedProviderId = BigInt(parsed.data.trainingProviderId);
  const scope = await resolveScope(projectId, req.auth!.userId);
  try { assertTpAssigned(scope); enforceProviderScope(scope, requestedProviderId); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
  try { await assertProjectRegistrationOpen(projectId, requestedProviderId); } catch (e) { return void res.status((e as any).status ?? 422).json({ error: (e as Error).message }); }

  const rosterRoleForCap = parseRosterRole(parsed.data.rosterRole);
  if (rosterRoleIsTrackedMember(rosterRoleForCap)) {
    try {
      await assertCanRegisterTrainees(prisma, projectId, requestedProviderId, 1);
    } catch (e) {
      return void res.status((e as { status?: number }).status ?? 422).json({ error: (e as Error).message });
    }
  }

  const requestedTrainingId = parsed.data.trainingId ? BigInt(parsed.data.trainingId) : null;
  const requestedCohortId = parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null;
  let trainingId: bigint | null = null;
  let cohortId: bigint | null = null;
  let batchId: bigint | null = null;
  let locationId: bigint | null = null;
  let trainingDurationId: bigint | null = null;
  if (requestedTrainingId) {
    try {
      const resolved = await resolveTrainingScope({
        prisma,
        projectId,
        trainingProviderId: requestedProviderId,
        trainingId: requestedTrainingId,
        cohortId: requestedCohortId,
      });
      trainingId = resolved.trainingId;
      cohortId = resolved.effectiveCohortId;
      locationId = resolved.effectiveLocationId;
      trainingDurationId = resolved.effectiveTrainingDurationId;
      batchId = await resolveTraineeDeliveryBatchId({
        prisma,
        cohortId: resolved.effectiveCohortId,
        explicitBatchId: parsed.data.batchId ? BigInt(parsed.data.batchId) : null,
        deliveryBatchCode: parsed.data.deliveryBatchCode,
      });
    } catch (e) {
      const status = (e as { status?: number }).status ?? 400;
      return void res.status(status).json({ error: e instanceof Error ? e.message : "Invalid training scope." });
    }
    if (parsed.data.locationId && BigInt(parsed.data.locationId) !== locationId) {
      return void res.status(422).json({ error: "locationId does not match resolved training/cohort scope." });
    }
    if (parsed.data.trainingDurationId && BigInt(parsed.data.trainingDurationId) !== trainingDurationId) {
      return void res.status(422).json({ error: "trainingDurationId does not match resolved training scope." });
    }
  } else {
    batchId = null;
  }

  const rosterRole = parseRosterRole(parsed.data.rosterRole);

  try {
    const phoneErr = phonePrimaryValidationError(parsed.data.phonePrimary);
    if (phoneErr) return void res.status(422).json({ error: phoneErr });
    await assertPhonePrimaryUniqueInProject({
      projectId,
      phonePrimary: parsed.data.phonePrimary || null,
    });
    await assertExternalBeneficiaryIdUniqueInProviderScope({
      projectId,
      trainingProviderId: requestedProviderId,
      externalBeneficiaryId: parsed.data.externalBeneficiaryId || null,
    });
  } catch (e) {
    return void res.status(422).json({ error: (e as Error).message });
  }

  const createData = {
    projectId,
    trainingProviderId: requestedProviderId,
    trainingId,
    cohortId,
    batchId,
    locationId,
    trainingDurationId,
    trainingType: parsed.data.trainingType || null,
    trainingLocation: parsed.data.trainingLocation || null,
    externalBeneficiaryId: normalizeExternalBeneficiaryId(parsed.data.externalBeneficiaryId),
    dateOfFormCompletion: parsed.data.dateOfFormCompletion ? new Date(parsed.data.dateOfFormCompletion) : null,
    firstName: parsed.data.firstName.trim(),
    fatherName: parsed.data.fatherName || null,
    grandfatherName: parsed.data.grandfatherName || null,
    sex: parsed.data.sex,
    ageYears: parsed.data.ageYears ?? null,
    dateOfBirthEtCalendar: parsed.data.dateOfBirthEtCalendar || null,
    phonePrimary: normalizePhone(parsed.data.phonePrimary) || null,
    phoneAlternative: normalizePhone(parsed.data.phoneAlternative) || null,
    email: parsed.data.email || null,
    kebele: parsed.data.kebele || null,
    woreda: parsed.data.woreda || null,
    subCity: parsed.data.subCity || null,
    region: parsed.data.region || null,
    emergencyContactName: parsed.data.emergencyContactName || null,
    emergencyContactPhone: normalizePhone(parsed.data.emergencyContactPhone) || null,
    highestEducation: normalizeHighestEducation(parsed.data.highestEducation) || null,
    previouslyParticipated: parsed.data.previouslyParticipated ?? null,
    priorTrainingType: parsed.data.priorTrainingType || null,
    priorCompleted: parsed.data.priorCompleted ?? null,
    priorYearCompleted: parsed.data.priorYearCompleted ?? null,
    employmentStatus: normalizeEmploymentStatus(parsed.data.employmentStatus) || null,
    incomeSufficient: parsed.data.incomeSufficient ?? null,
    skillUsage: parsed.data.skillUsage || null,
    postTrainingEmploymentPlanType: parsed.data.postTrainingEmploymentPlanType || null,
    postTrainingEmploymentPlanOtherText: parsed.data.postTrainingEmploymentPlanOtherText || null,
    disabilityFlag: parsed.data.disabilityFlag ?? null,
    disabilityType: parsed.data.disabilityType || null,
    disabilityOtherText: parsed.data.disabilityOtherText || null,
    idpFlag: parsed.data.idpFlag ?? null,
    returneeFlag: parsed.data.returneeFlag ?? null,
    lowIncomeFlag: parsed.data.lowIncomeFlag ?? null,
    inclusionNoneOfAbove: parsed.data.inclusionNoneOfAbove ?? null,
    inclusionPreferNotToSay: parsed.data.inclusionPreferNotToSay ?? null,
    consentAccuracy: parsed.data.consentAccuracy ?? null,
    consentFollowupSurveys: parsed.data.consentFollowupSurveys ?? null,
    consentContactVerify: parsed.data.consentContactVerify ?? null,
    consentImageUse: parsed.data.consentImageUse ?? null,
    rawPayload: parsed.data.rawPayload ?? undefined,
    rosterRole,
    attendanceEligibleFrom: null,
  };

  let created: Awaited<ReturnType<typeof prisma.trainee.create>> | null = null;
  for (let attempt = 0; attempt < 8; attempt += 1) {
    try {
      const generatedId = await generateScopedTraineeUniqueId(prisma, {
        projectId,
        trainingProviderId: requestedProviderId,
      });
      created = await prisma.trainee.create({
        data: {
          ...createData,
          traineeUniqueId: generatedId,
        },
      });
      break;
    } catch (e) {
      const known = e as Prisma.PrismaClientKnownRequestError;
      if (known?.code === "P2002" && attempt < 7) continue;
      throw e;
    }
  }
  if (!created) return void res.status(500).json({ error: "Could not generate unique trainee ID." });
  if (created.trainingId && countsAsActiveCohortMember(created.rosterRole)) {
    await prisma.traineeEnrollment.upsert({
      where: { trainingId_traineeId: { trainingId: created.trainingId, traineeId: created.id } },
      create: {
        projectId,
        trainingProviderId: created.trainingProviderId,
        trainingId: created.trainingId,
        cohortId: created.cohortId,
        batchId: created.batchId,
        traineeId: created.id,
        enrollmentStatus: "active",
      },
      update: { enrollmentStatus: "active", exitedAt: null },
    });
  }
  await audit({
    projectId,
    trainingProviderId: created.trainingProviderId,
    trainingId: created.trainingId,
    cohortId: created.cohortId,
    batchId: created.batchId,
    action: "trainee_created",
    sourceType: "trainee",
    sourceRef: created.id.toString(),
    payloadRaw: JSON.stringify({ traineeUniqueId: created.traineeUniqueId }),
    actorUserId: req.auth!.userId,
  });
  res.json({ item: { id: asId(created.id), traineeUniqueId: created.traineeUniqueId } });
});

router.post("/projects/:projectId/trainees/import", requirePermission("import:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const parsed = z.object({
    rows: z.array(z.record(z.any())).min(1),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const projectId = BigInt(req.params.projectId);
  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 rowsWithIndex = parsed.data.rows.map((row, idx) => ({
    row,
    rowIndex: idx + 1,
    csvRowNumber: idx + 2,
    traineeName: traineeRowLabel(row),
  }));
  const importProviderIds = new Set<bigint>();
  for (const { row } of rowsWithIndex) {
    if (!row.trainingProviderId) continue;
    try {
      importProviderIds.add(BigInt(row.trainingProviderId));
    } catch {
      /* row validation will report invalid id */
    }
  }
  try {
    if (scope.providerId) {
      await assertProjectRegistrationOpen(projectId, scope.providerId);
    } else {
      for (const pid of importProviderIds) {
        await assertProjectRegistrationOpen(projectId, pid);
      }
    }
  } catch (e) {
    return void res.status((e as any).status ?? 422).json({ error: (e as Error).message });
  }
  const rowErrors: Array<{ rowNumber: number; csvRowNumber: number; traineeName: string; errors: string[] }> = [];
  const parsedDatesByRow = new Map<
    number,
    { dateOfFormCompletion: Date | null; dateOfBirthEtCalendar: string | null }
  >();
  const resolvedScopeByRow = new Map<
    number,
    { locationId: bigint | null; trainingDurationId: bigint | null; cohortId: bigint | null; batchId: bigint | null }
  >();
  const normText = (s: string) => s.trim().toLowerCase().replace(/\s+/g, " ");
  const phoneRows = new Map<string, number[]>();
  const externalIdsByProviderInFile = new Map<string, number[]>();

  for (const { row, csvRowNumber } of rowsWithIndex) {
    const p = canonicalPhoneKey(row.phonePrimary ?? row.phone_primary);
    if (p) {
      const arr = phoneRows.get(p) ?? [];
      arr.push(csvRowNumber);
      phoneRows.set(p, arr);
    }
    const ext = normalizeExternalBeneficiaryId(
      row.externalBeneficiaryId ?? row.external_beneficiary_id ?? row.providerBeneficiaryId ?? row.provider_beneficiary_id,
    );
    if (!ext || !row.trainingProviderId) continue;
    const extKey = `${String(row.trainingProviderId)}::${ext}`;
    const extRows = externalIdsByProviderInFile.get(extKey) ?? [];
    extRows.push(csvRowNumber);
    externalIdsByProviderInFile.set(extKey, extRows);
  }

  const existingPhoneByKey = new Map<string, { firstName: string; phonePrimary: string }>();
  const existingTraineesWithPhone = await prisma.trainee.findMany({
    where: { projectId, phonePrimary: { not: null } },
    select: { phonePrimary: true, firstName: true, fatherName: true },
  });
  for (const t of existingTraineesWithPhone) {
    const k = canonicalPhoneKey(t.phonePrimary);
    if (!k || existingPhoneByKey.has(k)) continue;
    existingPhoneByKey.set(k, {
      firstName: [t.firstName, t.fatherName].filter(Boolean).join(" "),
      phonePrimary: t.phonePrimary!,
    });
  }

  for (const { row, rowIndex, csvRowNumber, traineeName } of rowsWithIndex) {
    const errors: string[] = [];
    if (!row.trainingProviderId) errors.push("Missing trainingProviderId");
    if (!row.firstName || !String(row.firstName).trim()) errors.push("Missing firstName");
    if (!row.sex || !String(row.sex).trim()) errors.push("Missing sex");
    if (!row.ageYears || Number.isNaN(Number(row.ageYears))) errors.push("Invalid ageYears");
    const phoneRaw = row.phonePrimary ?? row.phone_primary;
    if (!phoneRaw || !String(phoneRaw).trim()) errors.push("Missing phonePrimary");
    else {
      const phoneErr = phonePrimaryValidationError(phoneRaw);
      if (phoneErr) errors.push(phoneErr);
    }
    const phoneKey = canonicalPhoneKey(phoneRaw);
    if (phoneKey) {
      const dupRows = phoneRows.get(phoneKey) ?? [];
      if (dupRows.length > 1) errors.push(`Duplicate phonePrimary in file (CSV rows: ${dupRows.join(", ")})`);
      const existing = existingPhoneByKey.get(phoneKey);
      if (existing) {
        errors.push(
          `phonePrimary already exists in this project (${existing.firstName || "existing trainee"}, stored as ${existing.phonePrimary})`,
        );
      }
    }
    const formDate = parseTraineeFormCompletionDate(row.dateOfFormCompletion ?? row.date_of_form_completion);
    if (formDate.error) errors.push(formDate.error);
    const dobEt = normalizeEtCalendarDateText(row.dateOfBirthEtCalendar ?? row.date_of_birth_et_calendar);
    if (dobEt.error) errors.push(dobEt.error);
    if (!errors.length) {
      parsedDatesByRow.set(rowIndex, {
        dateOfFormCompletion: formDate.date,
        dateOfBirthEtCalendar: dobEt.text,
      });
    }
    const rosterRaw = String((row.roster_role ?? row.rosterRole ?? row.is_backup ?? "")).trim().toLowerCase();
    if (!rosterRaw) {
      errors.push("Missing rosterRole (use active or reserve)");
    } else if (!["active", "reserve", "backup", "true", "1"].includes(rosterRaw)) {
      errors.push("Invalid rosterRole (use active or reserve)");
    }

    let rowProviderId: bigint | null = null;
    try {
      rowProviderId = BigInt(row.trainingProviderId);
    } catch {
      errors.push("Invalid trainingProviderId");
    }
    if (scope.providerId && rowProviderId && scope.providerId !== rowProviderId) {
      errors.push("TP users can only import trainees under their own provider");
    }
    if (rowProviderId) {
      const provider = await prisma.trainingProvider.findFirst({
        where: { id: rowProviderId, projectId },
        select: { id: true, requireExternalBeneficiaryId: true },
      });
      if (!provider) {
        errors.push("Provider does not belong to this project");
      } else {
        const ext = normalizeExternalBeneficiaryId(
          row.externalBeneficiaryId ?? row.external_beneficiary_id ?? row.providerBeneficiaryId ?? row.provider_beneficiary_id,
        );
        if (provider.requireExternalBeneficiaryId && !ext) {
          errors.push("Missing external_beneficiary_id (required for this provider)");
        }
        if (ext) {
          const duplicateRows = externalIdsByProviderInFile.get(`${rowProviderId.toString()}::${ext}`) ?? [];
          if (duplicateRows.length > 1) {
            errors.push(
              `Duplicate external_beneficiary_id in file for this provider (CSV rows: ${duplicateRows.join(", ")})`,
            );
          }
          const existingExternal = await prisma.trainee.findFirst({
            where: { projectId, trainingProviderId: rowProviderId, externalBeneficiaryId: ext },
            select: { traineeUniqueId: true },
          });
          if (existingExternal) {
            errors.push(
              `external_beneficiary_id already exists for this provider (existing trainee ${existingExternal.traineeUniqueId})`,
            );
          }
        }
      }
    }
    if (row.trainingId) {
      let trainingId: bigint | null = null;
      try {
        trainingId = BigInt(row.trainingId);
      } catch {
        errors.push("Invalid trainingId");
      }
      if (trainingId && rowProviderId) {
        const training = await prisma.training.findFirst({
          where: { id: trainingId, projectId, trainingProviderId: rowProviderId },
          select: {
            id: true,
            locationId: true,
            trainingDurationId: true,
            trainingType: true,
            trainingDuration: { select: { months: true } },
          },
        });
        if (!training) {
          errors.push("Training does not belong to selected provider/project");
        } else {
          let effectiveLocationId: bigint | null = null;
          let effectiveTrainingDurationId: bigint | null = training.trainingDurationId ?? null;
          const csvTrainingType = typeof row.trainingType === "string" ? row.trainingType : String(row.training_type ?? "");
          if (!csvTrainingType || !csvTrainingType.trim()) {
            errors.push(`Scope mismatch: training_type is missing. Expected "${training.trainingType}" from selected training.`);
          } else if (normText(csvTrainingType) !== normText(training.trainingType ?? "")) {
            errors.push(
              `Scope mismatch: training_type must match selected training. Expected "${training.trainingType}", but CSV has "${csvTrainingType}".`,
            );
          }

          const rawPayload = (row.rawPayload ?? {}) as Record<string, unknown>;
          const csvDurationRaw =
            row.trainingDurationMonths ??
            row.training_duration_months ??
            rawPayload.training_duration_months ??
            rawPayload.trainingDurationMonths;
          const csvDuration = Number(csvDurationRaw);
          const scopedDurationMonths = training.trainingDuration?.months ?? null;
          if (scopedDurationMonths != null) {
            if (!Number.isFinite(csvDuration)) {
              errors.push(
                `Scope mismatch: training_duration_months is missing/invalid. Expected ${scopedDurationMonths} month(s) from selected training.`,
              );
            } else if (Math.trunc(csvDuration) !== scopedDurationMonths) {
              errors.push(
                `Scope mismatch: training_duration_months must match selected training. Expected ${scopedDurationMonths}, but CSV has ${Math.trunc(csvDuration)}.`,
              );
            }
          }
          const cohortRows = await prisma.trainingCohort.findMany({
            where: { projectId, trainingProviderId: rowProviderId, trainingId },
            select: { id: true, locationId: true },
            orderBy: { id: "asc" },
          });
          if (cohortRows.length === 0) {
            errors.push("Training has no cohorts configured.");
          } else if (cohortRows.length > 1 && !row.cohortId) {
            errors.push("cohortId is required because the training has multiple cohorts");
          } else {
            let locCohortId: bigint | null = null;
            if (row.cohortId) {
              try {
                locCohortId = BigInt(row.cohortId);
              } catch {
                errors.push("Invalid cohortId");
              }
            } else if (cohortRows.length === 1) {
              locCohortId = cohortRows[0]!.id;
            }
            if (locCohortId && rowProviderId && trainingId) {
              const cohort = cohortRows.find((c) => c.id === locCohortId);
              if (!cohort) errors.push("Cohort does not belong to selected training/provider/project");
              else effectiveLocationId = cohort.locationId ?? training.locationId ?? null;
            }
          }

          const rawLocationText =
            typeof rawPayload.training_location === "string"
              ? rawPayload.training_location
              : typeof rawPayload.trainingLocation === "string"
                ? rawPayload.trainingLocation
                : typeof row.trainingLocation === "string"
                  ? row.trainingLocation
                  : typeof row.training_location === "string"
                    ? row.training_location
                    : null;
          if (rawLocationText && effectiveLocationId) {
            const loc = await prisma.location.findFirst({
              where: { id: effectiveLocationId },
              select: { name: true },
            });
            if (loc?.name && normText(rawLocationText) !== normText(loc.name)) {
              errors.push(
                `Scope mismatch: training_location must match selected cohort location. Expected "${loc.name}", but CSV has "${rawLocationText}".`,
              );
            }
          } else if (effectiveLocationId && !rawLocationText) {
            errors.push("Scope mismatch: training_location is missing. It must match the selected training/cohort location.");
          }

          if (row.locationId) {
            try {
              const requestedLocationId = BigInt(row.locationId);
              if (effectiveLocationId && requestedLocationId !== effectiveLocationId) {
                errors.push("locationId does not match selected training/cohort scope");
              }
            } catch {
              errors.push("Invalid locationId");
            }
          }
          if (row.trainingDurationId) {
            try {
              const requestedDurationId = BigInt(row.trainingDurationId);
              if (effectiveTrainingDurationId && requestedDurationId !== effectiveTrainingDurationId) {
                errors.push("trainingDurationId does not match selected training");
              }
            } catch {
              errors.push("Invalid trainingDurationId");
            }
          }
          let cohortIdResolved: bigint | null = null;
          let batchIdResolved: bigint | null = null;
          if (errors.length === 0 && trainingId && rowProviderId) {
            try {
              const requestedCohortCsv = row.cohortId ? BigInt(String(row.cohortId)) : null;
              const scoped = await resolveTrainingScope({
                prisma,
                projectId,
                trainingProviderId: rowProviderId,
                trainingId,
                cohortId: requestedCohortCsv,
              });
              cohortIdResolved = scoped.effectiveCohortId;

              let explicitBatchId: bigint | null = null;
              const batchIdRaw = row.batchId ?? row.batch_id ?? row.deliveryBatchId ?? row.delivery_batch_id;
              if (batchIdRaw !== undefined && batchIdRaw !== null && String(batchIdRaw).trim() !== "") {
                try {
                  explicitBatchId = BigInt(String(batchIdRaw));
                } catch {
                  throw new Error("Invalid batchId.");
                }
              }
              const codeRaw =
                row.delivery_batch_code ?? row.deliveryBatchCode ?? row.batch_code ?? row.batchCode;
              const deliveryBatchCode =
                typeof codeRaw === "string" && codeRaw.trim().length > 0 ? codeRaw.trim() : undefined;
              batchIdResolved = await resolveTraineeDeliveryBatchId({
                prisma,
                cohortId: cohortIdResolved,
                explicitBatchId,
                deliveryBatchCode,
              });
            } catch (e) {
              errors.push(e instanceof Error ? e.message : "Invalid training cohort or delivery batch.");
            }
          }
          resolvedScopeByRow.set(rowIndex, {
            locationId: effectiveLocationId,
            trainingDurationId: effectiveTrainingDurationId,
            cohortId: cohortIdResolved,
            batchId: batchIdResolved,
          });
        }
      } else if (row.cohortId) {
        errors.push("cohortId cannot be provided without trainingId");
      }
      if (row.cohortId && row.trainingId) {
        let cohortId: bigint | null = null;
        try {
          cohortId = BigInt(row.cohortId);
        } catch {
          errors.push("Invalid cohortId");
        }
        if (cohortId && rowProviderId && trainingId) {
          const cohort = await prisma.trainingCohort.findFirst({
            where: { id: cohortId, projectId, trainingProviderId: rowProviderId, trainingId },
            select: { id: true },
          });
          if (!cohort) errors.push("Cohort does not belong to selected training/provider/project");
        }
      }
    } else if (row.locationId || row.trainingDurationId) {
      errors.push("locationId/trainingDurationId require trainingId");
    }
    if (errors.length) rowErrors.push({ rowNumber: rowIndex, csvRowNumber, traineeName, errors });
  }

  if (rowErrors.length) {
    return void res.status(422).json({
      error: "Import validation failed. No rows were imported.",
      rowErrors,
    });
  }

  const newTrackedByProvider = new Map<string, number>();
  for (const { row } of rowsWithIndex) {
    const role = parseRosterRole(row.roster_role ?? row.rosterRole ?? row.is_backup);
    if (!rosterRoleIsTrackedMember(role)) continue;
    const tpKey = String(row.trainingProviderId);
    newTrackedByProvider.set(tpKey, (newTrackedByProvider.get(tpKey) ?? 0) + 1);
  }
  for (const [tpKey, addCount] of newTrackedByProvider) {
    try {
      await assertCanRegisterTrainees(prisma, projectId, BigInt(tpKey), addCount);
    } catch (e) {
      return void res.status(422).json({ error: (e as Error).message });
    }
  }

  const importTxMs = Math.min(120_000, Math.max(15_000, rowsWithIndex.length * 400));

  const created = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
    const inserted: Array<{ id: string; traineeUniqueId: string }> = [];
    for (const { row, rowIndex, csvRowNumber } of rowsWithIndex) {
      const resolved = resolvedScopeByRow.get(rowIndex) ?? {
        locationId: null,
        trainingDurationId: null,
        cohortId: null,
        batchId: null,
      };
      const trainingProviderId = BigInt(row.trainingProviderId);
      const rosterRole = parseRosterRole(row.roster_role ?? row.rosterRole ?? row.is_backup);
      const baseData = {
        projectId,
        trainingProviderId,
        trainingId: row.trainingId ? BigInt(row.trainingId) : null,
        cohortId: resolved.cohortId ?? (row.cohortId ? BigInt(row.cohortId) : null),
        batchId: resolved.batchId,
        locationId: resolved.locationId,
        trainingDurationId: resolved.trainingDurationId,
        firstName: String(row.firstName || ""),
        fatherName: row.fatherName ? String(row.fatherName) : null,
        grandfatherName: row.grandfatherName ? String(row.grandfatherName) : null,
        sex: String(row.sex || "Unknown"),
        ageYears: typeof row.ageYears === "number" ? row.ageYears : Number(row.ageYears),
        dateOfBirthEtCalendar:
          parsedDatesByRow.get(rowIndex)?.dateOfBirthEtCalendar ??
          (row.dateOfBirthEtCalendar ? String(row.dateOfBirthEtCalendar) : null),
        phonePrimary: normalizePhone(row.phonePrimary) || null,
        phoneAlternative: normalizePhone(row.phoneAlternative) || null,
        email: row.email ? String(row.email) : null,
        kebele: row.kebele ? String(row.kebele) : null,
        woreda: row.woreda ? String(row.woreda) : null,
        subCity: row.subCity ? String(row.subCity) : null,
        region: row.region ? String(row.region) : null,
        emergencyContactName: row.emergencyContactName ? String(row.emergencyContactName) : null,
        emergencyContactPhone: normalizePhone(row.emergencyContactPhone) || null,
        highestEducation: normalizeHighestEducation(row.highestEducation ? String(row.highestEducation) : null),
        previouslyParticipated: typeof row.previouslyParticipated === "boolean" ? row.previouslyParticipated : null,
        priorTrainingType: row.priorTrainingType ? String(row.priorTrainingType) : null,
        priorCompleted: typeof row.priorCompleted === "boolean" ? row.priorCompleted : null,
        priorYearCompleted: typeof row.priorYearCompleted === "number" ? row.priorYearCompleted : null,
        employmentStatus: normalizeEmploymentStatus(row.employmentStatus ? String(row.employmentStatus) : null),
        incomeSufficient: typeof row.incomeSufficient === "boolean" ? row.incomeSufficient : null,
        skillUsage: row.skillUsage ? String(row.skillUsage) : null,
        postTrainingEmploymentPlanType: row.postTrainingEmploymentPlanType ? String(row.postTrainingEmploymentPlanType) : null,
        postTrainingEmploymentPlanOtherText: row.postTrainingEmploymentPlanOtherText ? String(row.postTrainingEmploymentPlanOtherText) : null,
        disabilityFlag: typeof row.disabilityFlag === "boolean" ? row.disabilityFlag : null,
        disabilityType: row.disabilityType ? String(row.disabilityType) : null,
        disabilityOtherText: row.disabilityOtherText ? String(row.disabilityOtherText) : null,
        idpFlag: typeof row.idpFlag === "boolean" ? row.idpFlag : null,
        returneeFlag: typeof row.returneeFlag === "boolean" ? row.returneeFlag : null,
        lowIncomeFlag: typeof row.lowIncomeFlag === "boolean" ? row.lowIncomeFlag : null,
        inclusionNoneOfAbove: typeof row.inclusionNoneOfAbove === "boolean" ? row.inclusionNoneOfAbove : null,
        inclusionPreferNotToSay: typeof row.inclusionPreferNotToSay === "boolean" ? row.inclusionPreferNotToSay : null,
        consentAccuracy: typeof row.consentAccuracy === "boolean" ? row.consentAccuracy : null,
        consentFollowupSurveys: typeof row.consentFollowupSurveys === "boolean" ? row.consentFollowupSurveys : null,
        consentContactVerify: typeof row.consentContactVerify === "boolean" ? row.consentContactVerify : null,
        consentImageUse: typeof row.consentImageUse === "boolean" ? row.consentImageUse : null,
        trainingType: row.trainingType ? String(row.trainingType) : null,
        trainingLocation: row.trainingLocation ? String(row.trainingLocation) : null,
        externalBeneficiaryId: normalizeExternalBeneficiaryId(
          row.externalBeneficiaryId ?? row.external_beneficiary_id ?? row.providerBeneficiaryId ?? row.provider_beneficiary_id,
        ),
        dateOfFormCompletion: parsedDatesByRow.get(rowIndex)?.dateOfFormCompletion ?? null,
        rawPayload: { ...row, _importCsvRowNumber: csvRowNumber },
        rosterRole,
      };
      let insert: Awaited<ReturnType<typeof tx.trainee.create>> | null = null;
      for (let attempt = 0; attempt < 8; attempt += 1) {
        try {
          const traineeUniqueId = await generateScopedTraineeUniqueId(tx, { projectId, trainingProviderId });
          insert = await tx.trainee.create({
            data: {
              ...baseData,
              traineeUniqueId,
              attendanceEligibleFrom: null,
            },
          });
          break;
        } catch (e) {
          const known = e as Prisma.PrismaClientKnownRequestError;
          if (known?.code === "P2002" && attempt < 7) continue;
          throw e;
        }
      }
      if (!insert) throw new Error("Could not generate unique trainee ID during import.");
      if (insert.trainingId && countsAsActiveCohortMember(insert.rosterRole)) {
        await tx.traineeEnrollment.upsert({
          where: { trainingId_traineeId: { trainingId: insert.trainingId, traineeId: insert.id } },
          create: {
            projectId,
            trainingProviderId: insert.trainingProviderId,
            trainingId: insert.trainingId,
            cohortId: insert.cohortId,
            batchId: insert.batchId,
            traineeId: insert.id,
            enrollmentStatus: "active",
          },
          update: { enrollmentStatus: "active", exitedAt: null },
        });
      }
      inserted.push({ id: asId(insert.id), traineeUniqueId: insert.traineeUniqueId });
    }
    return inserted;
  }, { maxWait: importTxMs, timeout: importTxMs });

  await audit({
    projectId,
    action: "trainee_imported",
    sourceType: "import",
    sourceRef: "trainees",
    payloadRaw: JSON.stringify({ createdCount: created.length }),
    actorUserId: req.auth!.userId,
  });
  res.json({ createdCount: created.length, items: created });
});

router.get("/projects/:projectId/trainees/:traineeId", requirePermission("view:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const traineeId = parseTraineeIdParam(req.params.traineeId);
  if (traineeId == null) return void res.status(404).json({ error: "Trainee not found." });
  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 t = await prisma.trainee.findFirst({
    where: { id: traineeId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    include: {
      training: true,
      trainingProvider: true,
      batch: { select: { id: true, code: true, name: true } },
      replacedTrainee: { select: { id: true, traineeUniqueId: true, firstName: true } },
      traineesReplacingThisRow: { select: { id: true, traineeUniqueId: true, firstName: true } },
    },
  });
  if (!t) return void res.status(404).json({ error: "Trainee not found." });
  res.json({
    item: {
      id: asId(t.id),
      traineeUniqueId: t.traineeUniqueId,
      firstName: t.firstName,
      fatherName: t.fatherName,
      grandfatherName: t.grandfatherName,
      sex: t.sex,
      ageYears: t.ageYears,
      dateOfBirthEtCalendar: t.dateOfBirthEtCalendar,
      phonePrimary: t.phonePrimary,
      phoneAlternative: t.phoneAlternative,
      email: t.email,
      kebele: t.kebele,
      woreda: t.woreda,
      subCity: t.subCity,
      region: t.region,
      emergencyContactName: t.emergencyContactName,
      emergencyContactPhone: t.emergencyContactPhone,
      highestEducation: t.highestEducation,
      employmentStatus: t.employmentStatus,
      previouslyParticipated: t.previouslyParticipated,
      priorTrainingType: t.priorTrainingType,
      priorCompleted: t.priorCompleted,
      priorYearCompleted: t.priorYearCompleted,
      incomeSufficient: t.incomeSufficient,
      skillUsage: t.skillUsage,
      postTrainingEmploymentPlanType: t.postTrainingEmploymentPlanType,
      postTrainingEmploymentPlanOtherText: t.postTrainingEmploymentPlanOtherText,
      disabilityFlag: t.disabilityFlag,
      disabilityType: t.disabilityType,
      disabilityOtherText: t.disabilityOtherText,
      idpFlag: t.idpFlag,
      returneeFlag: t.returneeFlag,
      lowIncomeFlag: t.lowIncomeFlag,
      inclusionNoneOfAbove: t.inclusionNoneOfAbove,
      inclusionPreferNotToSay: t.inclusionPreferNotToSay,
      consentAccuracy: t.consentAccuracy,
      consentFollowupSurveys: t.consentFollowupSurveys,
      consentContactVerify: t.consentContactVerify,
      consentImageUse: t.consentImageUse,
      trainingType: t.trainingType,
      trainingLocation: t.trainingLocation,
      externalBeneficiaryId: t.externalBeneficiaryId,
      dateOfFormCompletion: t.dateOfFormCompletion ? t.dateOfFormCompletion.toISOString() : null,
      createdAt: t.createdAt.toISOString(),
      updatedAt: t.updatedAt.toISOString(),
      trainingProviderId: asId(t.trainingProviderId),
      trainingId: t.trainingId ? asId(t.trainingId) : null,
      cohortId: t.cohortId ? asId(t.cohortId) : null,
      batchId: t.batchId ? asId(t.batchId) : null,
      deliveryBatch: t.batch
        ? { id: asId(t.batch.id), code: t.batch.code, name: t.batch.name }
        : null,
      providerName: t.trainingProvider.name,
      trainingTitle: t.training?.title ?? null,
      rawPayload: t.rawPayload ?? null,
      rosterRole: t.rosterRole,
      attendanceEligibleFrom: t.attendanceEligibleFrom ? t.attendanceEligibleFrom.toISOString().slice(0, 10) : null,
      replacesTraineeId: t.replacesTraineeId ? asId(t.replacesTraineeId) : null,
      replacedTrainee: t.replacedTrainee
        ? {
            id: asId(t.replacedTrainee.id),
            traineeUniqueId: t.replacedTrainee.traineeUniqueId,
            firstName: t.replacedTrainee.firstName,
          }
        : null,
      traineesReplacingThisRow: t.traineesReplacingThisRow.map((x) => ({
        id: asId(x.id),
        traineeUniqueId: x.traineeUniqueId,
        firstName: x.firstName,
      })),
    },
  });
});

router.put("/projects/:projectId/trainees/:traineeId", requirePermission("edit:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const projectId = BigInt(req.params.projectId);
  const traineeId = parseTraineeIdParam(req.params.traineeId);
  if (traineeId == null) return void res.status(404).json({ error: "Trainee not found." });
  const parsed = z.object({
    trainingProviderId: z.string(),
    trainingId: z.string().optional(),
    cohortId: z.string().optional(),
    batchId: z.string().regex(/^\d+$/).optional(),
    deliveryBatchCode: z.string().min(1).max(64).optional(),
    locationId: z.string().optional(),
    trainingDurationId: z.string().optional(),
    trainingType: z.string().optional(),
    trainingLocation: z.string().optional(),
    dateOfFormCompletion: z.string().optional(),
    firstName: z.string().min(1),
    fatherName: z.string().optional(),
    grandfatherName: z.string().optional(),
    sex: z.string().min(1),
    ageYears: z.number().int().optional(),
    dateOfBirthEtCalendar: z.string().optional(),
    phonePrimary: z.string().optional(),
    phoneAlternative: z.string().optional(),
    email: optionalEmailField,
    kebele: z.string().optional(),
    woreda: z.string().optional(),
    subCity: z.string().optional(),
    region: z.string().optional(),
    emergencyContactName: z.string().optional(),
    emergencyContactPhone: z.string().optional(),
    highestEducation: z.string().optional(),
    previouslyParticipated: z.boolean().optional(),
    priorTrainingType: z.string().optional(),
    priorCompleted: z.boolean().optional(),
    priorYearCompleted: z.number().int().optional(),
    employmentStatus: z.string().optional(),
    incomeSufficient: z.boolean().optional(),
    skillUsage: z.string().optional(),
    postTrainingEmploymentPlanType: z.string().optional(),
    postTrainingEmploymentPlanOtherText: z.string().optional(),
    disabilityFlag: z.boolean().optional(),
    disabilityType: z.string().optional(),
    disabilityOtherText: z.string().optional(),
    idpFlag: z.boolean().optional(),
    returneeFlag: z.boolean().optional(),
    lowIncomeFlag: z.boolean().optional(),
    inclusionNoneOfAbove: z.boolean().optional(),
    inclusionPreferNotToSay: z.boolean().optional(),
    consentAccuracy: z.boolean().optional(),
    consentFollowupSurveys: z.boolean().optional(),
    consentContactVerify: z.boolean().optional(),
    consentImageUse: z.boolean().optional(),
    externalBeneficiaryId: z.string().optional(),
    rawPayload: z.record(z.any()).optional(),
    rosterRole: z.string().optional(),
  }).safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });

  const requestedProviderId = BigInt(parsed.data.trainingProviderId);
  const scope = await resolveScope(projectId, req.auth!.userId);
  try { assertTpAssigned(scope); enforceProviderScope(scope, requestedProviderId); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
  try { await assertProjectRegistrationOpen(projectId, requestedProviderId); } catch (e) { return void res.status((e as any).status ?? 422).json({ error: (e as Error).message }); }
  const existingTrainee = await prisma.trainee.findFirst({
    where: { id: traineeId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: {
      id: true,
      rosterRole: true,
      attendanceEligibleFrom: true,
      trainingId: true,
      cohortId: true,
      batchId: true,
    },
  });
  if (!existingTrainee) return void res.status(404).json({ error: "Trainee not found." });
  try {
    if (parsed.data.phonePrimary !== undefined) {
      const phoneErr = phonePrimaryValidationError(parsed.data.phonePrimary);
      if (phoneErr) return void res.status(422).json({ error: phoneErr });
    }
    await assertPhonePrimaryUniqueInProject({
      projectId,
      phonePrimary: parsed.data.phonePrimary || null,
      excludeTraineeId: traineeId,
    });
    await assertExternalBeneficiaryIdUniqueInProviderScope({
      projectId,
      trainingProviderId: requestedProviderId,
      externalBeneficiaryId: parsed.data.externalBeneficiaryId || null,
      excludeTraineeId: traineeId,
    });
  } catch (e) {
    return void res.status(422).json({ error: (e as Error).message });
  }

  const requestedTrainingId = parsed.data.trainingId ? BigInt(parsed.data.trainingId) : null;
  const requestedCohortId = parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null;
  let trainingId: bigint | null = null;
  let cohortId: bigint | null = null;
  let batchId: bigint | null = null;
  let locationId: bigint | null = null;
  let trainingDurationId: bigint | null = null;
  if (requestedTrainingId) {
    const cohortIdForResolve =
      requestedCohortId ??
      (existingTrainee.trainingId?.toString() === requestedTrainingId.toString() ? existingTrainee.cohortId : null);
    try {
      const resolved = await resolveTrainingScope({
        prisma,
        projectId,
        trainingProviderId: requestedProviderId,
        trainingId: requestedTrainingId,
        cohortId: cohortIdForResolve,
      });
      trainingId = resolved.trainingId;
      cohortId = resolved.effectiveCohortId;
      locationId = resolved.effectiveLocationId;
      trainingDurationId = resolved.effectiveTrainingDurationId;
      batchId = await resolveTraineeDeliveryBatchId({
        prisma,
        cohortId: resolved.effectiveCohortId,
        explicitBatchId:
          parsed.data.batchId
            ? BigInt(parsed.data.batchId)
            : existingTrainee.trainingId?.toString() === requestedTrainingId.toString()
              ? existingTrainee.batchId
              : null,
        deliveryBatchCode: parsed.data.deliveryBatchCode,
      });
    } catch (e) {
      const status = (e as { status?: number }).status ?? 400;
      return void res.status(status).json({ error: e instanceof Error ? e.message : "Invalid training scope." });
    }
    if (parsed.data.locationId && BigInt(parsed.data.locationId) !== locationId) {
      return void res.status(422).json({ error: "locationId does not match resolved training/cohort scope." });
    }
    if (parsed.data.trainingDurationId && BigInt(parsed.data.trainingDurationId) !== trainingDurationId) {
      return void res.status(422).json({ error: "trainingDurationId does not match resolved training scope." });
    }
  } else {
    batchId = null;
  }

  let nextRoster =
    parsed.data.rosterRole !== undefined ? parseRosterRole(parsed.data.rosterRole) : parseRosterRole(existingTrainee.rosterRole);
  if (
    (existingTrainee.rosterRole === "replaced_withdrawn" || existingTrainee.rosterRole === "reserve_withdrawn") &&
    parsed.data.rosterRole !== undefined &&
    parseRosterRole(parsed.data.rosterRole) !== parseRosterRole(existingTrainee.rosterRole)
  ) {
    return void res.status(422).json({ error: "Withdrawn roster roles cannot be changed." });
  }

  const updated = await prisma.trainee.update({
    where: { id: traineeId },
    data: {
      trainingProviderId: requestedProviderId,
      trainingId,
      cohortId,
      batchId,
      locationId,
      trainingDurationId,
      trainingType: parsed.data.trainingType || null,
      trainingLocation: parsed.data.trainingLocation || null,
      externalBeneficiaryId: normalizeExternalBeneficiaryId(parsed.data.externalBeneficiaryId),
      dateOfFormCompletion: parsed.data.dateOfFormCompletion ? new Date(parsed.data.dateOfFormCompletion) : null,
      firstName: parsed.data.firstName.trim(),
      fatherName: parsed.data.fatherName || null,
      grandfatherName: parsed.data.grandfatherName || null,
      sex: parsed.data.sex,
      ageYears: parsed.data.ageYears ?? null,
      dateOfBirthEtCalendar: parsed.data.dateOfBirthEtCalendar || null,
      phonePrimary: normalizePhone(parsed.data.phonePrimary) || null,
      phoneAlternative: normalizePhone(parsed.data.phoneAlternative) || null,
      email: parsed.data.email || null,
      kebele: parsed.data.kebele || null,
      woreda: parsed.data.woreda || null,
      subCity: parsed.data.subCity || null,
      region: parsed.data.region || null,
      emergencyContactName: parsed.data.emergencyContactName || null,
      emergencyContactPhone: normalizePhone(parsed.data.emergencyContactPhone) || null,
      highestEducation: normalizeHighestEducation(parsed.data.highestEducation) || null,
      previouslyParticipated: parsed.data.previouslyParticipated ?? null,
      priorTrainingType: parsed.data.priorTrainingType || null,
      priorCompleted: parsed.data.priorCompleted ?? null,
      priorYearCompleted: parsed.data.priorYearCompleted ?? null,
      employmentStatus: normalizeEmploymentStatus(parsed.data.employmentStatus) || null,
      incomeSufficient: parsed.data.incomeSufficient ?? null,
      skillUsage: parsed.data.skillUsage || null,
      postTrainingEmploymentPlanType: parsed.data.postTrainingEmploymentPlanType || null,
      postTrainingEmploymentPlanOtherText: parsed.data.postTrainingEmploymentPlanOtherText || null,
      disabilityFlag: parsed.data.disabilityFlag ?? null,
      disabilityType: parsed.data.disabilityType || null,
      disabilityOtherText: parsed.data.disabilityOtherText || null,
      idpFlag: parsed.data.idpFlag ?? null,
      returneeFlag: parsed.data.returneeFlag ?? null,
      lowIncomeFlag: parsed.data.lowIncomeFlag ?? null,
      inclusionNoneOfAbove: parsed.data.inclusionNoneOfAbove ?? null,
      inclusionPreferNotToSay: parsed.data.inclusionPreferNotToSay ?? null,
      consentAccuracy: parsed.data.consentAccuracy ?? null,
      consentFollowupSurveys: parsed.data.consentFollowupSurveys ?? null,
      consentContactVerify: parsed.data.consentContactVerify ?? null,
      consentImageUse: parsed.data.consentImageUse ?? null,
      rawPayload: parsed.data.rawPayload ?? undefined,
      rosterRole: nextRoster,
      attendanceEligibleFrom: null,
    },
    select: { id: true },
  });
  await prisma.traineeEnrollment.deleteMany({ where: { traineeId } });
  if (trainingId && countsAsActiveCohortMember(nextRoster)) {
    await prisma.traineeEnrollment.create({
      data: {
        projectId,
        trainingProviderId: requestedProviderId,
        trainingId,
        cohortId,
        batchId,
        traineeId,
        enrollmentStatus: "active",
      },
    });
  }
  await audit({
    projectId,
    trainingProviderId: requestedProviderId,
    trainingId,
    cohortId,
    batchId,
    action: "trainee_updated",
    sourceType: "trainee",
    sourceRef: traineeId.toString(),
    payloadRaw: JSON.stringify(parsed.data),
    actorUserId: req.auth!.userId,
  });
  res.json({ item: { id: asId(updated.id) } });
});

router.post("/projects/:projectId/trainees/replacement", requirePermission("edit:trainees", { projectIdParam: "projectId" }), async (_req: AuthedRequest, res) => {
  return void res.status(410).json({
    error:
      "Reserve replacement workflow is no longer available. Active and reserve trainees are tracked equally; update roster_role for reporting only.",
  });
});

async function scopedTrainee(req: AuthedRequest, res: Response) {
  const projectId = BigInt(req.params.projectId);
  const traineeId = parseTraineeIdParam(req.params.traineeId);
  if (traineeId == null) return void res.status(404).json({ error: "Trainee not found." });
  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 exists = await prisma.trainee.findFirst({
    where: { id: traineeId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    select: { id: true },
  });
  if (!exists) return void res.status(404).json({ error: "Trainee not found." });
  return { projectId, traineeId };
}

router.get("/projects/:projectId/trainees/:traineeId/delete-impact", requirePermission("delete:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const t = await scopedTrainee(req, res);
  if (!t) return;
  res.json({ item: await traineeDeleteImpact(t.projectId, t.traineeId) });
});

router.delete("/projects/:projectId/trainees/:traineeId", requirePermission("delete:trainees", { projectIdParam: "projectId" }), async (req: AuthedRequest, res) => {
  const parsed = z.object({ reason: z.string().trim().min(10).max(1000), confirmCode: z.string().trim() }).safeParse(req.body ?? {});
  if (!parsed.success) return void res.status(400).json({ error: "Give a reason (at least 10 characters) and type the trainee ID to confirm." });
  const t = await scopedTrainee(req, res);
  if (!t) return;
  const row = await prisma.trainee.findUnique({ where: { id: t.traineeId }, select: { traineeUniqueId: true } });
  const code = row?.traineeUniqueId ?? t.traineeId.toString();
  if (parsed.data.confirmCode.toLowerCase() !== code.toLowerCase()) return void res.status(422).json({ error: `Type ${code} to confirm.` });
  await deleteTraineeWithCopy({ projectId: t.projectId, traineeId: t.traineeId, reason: parsed.data.reason, actorUserId: req.auth!.userId });
  res.json({ ok: true });
});

router.get(
  "/projects/:projectId/trainings/:trainingId/breakdowns",
  requirePermission("view:trainings", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    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 rows = await prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      include: {
        cohort: { select: { id: true, code: true, name: true } },
        batch: { select: { id: true, code: true, name: true } },
      },
      orderBy: [{ createdAt: "desc" }, { id: "desc" }],
    });
    res.json({
      items: rows.map((r) => ({
        id: asId(r.id),
        trainingId: asId(r.trainingId),
        cohortId: r.cohortId ? asId(r.cohortId) : null,
        batchId: r.batchId ? asId(r.batchId) : null,
        cohortCode: r.cohort?.code ?? null,
        cohortName: r.cohort?.name ?? null,
        batchCode: r.batch?.code ?? null,
        batchName: r.batch?.name ?? null,
        breakStartDate: r.breakStartDate.toISOString().slice(0, 10),
        breakEndDate: r.breakEndDate.toISOString().slice(0, 10),
        reason: r.reason,
        status: r.status,
        requestedByUserId: r.requestedByUserId ? asId(r.requestedByUserId) : null,
        approvedByUserId: r.approvedByUserId ? asId(r.approvedByUserId) : null,
        approvedAt: r.approvedAt?.toISOString() ?? null,
      })),
    });
  },
);

router.post(
  "/projects/:projectId/trainings/:trainingId/breakdowns",
  requirePermission("request:training-breakdowns", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const parsed = z
      .object({
        cohortId: z.string().optional(),
        batchId: z.string().optional(),
        breakStartDate: z.string(),
        breakEndDate: z.string(),
        reason: z.string().min(3),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    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 training = await prisma.training.findFirst({
      where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      select: { id: true, trainingProviderId: true, startDate: true, timelineAnchorDate: true, endDate: true },
    });
    if (!training) return void res.status(404).json({ error: "Training not found." });
    if (parsed.data.breakEndDate < parsed.data.breakStartDate) {
      return void res.status(422).json({ error: "Breakdown end date must be on or after start date." });
    }
    const breakdownStart = dateOnlyUtc(parsed.data.breakStartDate);
    const breakdownEnd = dateOnlyUtc(parsed.data.breakEndDate);
    const requestedCohortId = parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null;
    const requestedBatchId = parsed.data.batchId ? BigInt(parsed.data.batchId) : null;
    let effectiveCohortId: bigint | null = null;
    let effectiveBatchId: bigint | null = null;
    let scopeStart = dateOnlyUtc(effectiveStartDate(training.startDate, training.timelineAnchorDate));
    let scopeEnd = dateOnlyUtc(training.endDate);
    if (requestedBatchId) {
      const batch = await prisma.trainingBatch.findFirst({
        where: {
          id: requestedBatchId,
          projectId,
          trainingId,
          trainingProviderId: training.trainingProviderId,
        },
        select: {
          id: true,
          cohortId: true,
          startDate: true,
          timelineAnchorDate: true,
          endDate: true,
        },
      });
      if (!batch) return void res.status(404).json({ error: "Selected delivery batch not found for this training." });
      if (requestedCohortId && requestedCohortId !== batch.cohortId) {
        return void res.status(422).json({ error: "batchId does not belong to the provided cohortId." });
      }
      effectiveCohortId = batch.cohortId;
      effectiveBatchId = batch.id;
      scopeStart = dateOnlyUtc(effectiveStartDate(batch.startDate, batch.timelineAnchorDate));
      scopeEnd = dateOnlyUtc(batch.endDate);
    } else if (requestedCohortId) {
      const cohort = await prisma.trainingCohort.findFirst({
        where: { id: requestedCohortId, projectId, trainingId, trainingProviderId: training.trainingProviderId },
        select: { id: true, startDate: true, timelineAnchorDate: true, endDate: true },
      });
      if (!cohort) return void res.status(404).json({ error: "Selected cohort not found for this training." });
      effectiveCohortId = cohort.id;
      scopeStart = dateOnlyUtc(effectiveStartDate(cohort.startDate, cohort.timelineAnchorDate));
      scopeEnd = dateOnlyUtc(cohort.endDate);
    }
    if (breakdownStart < scopeStart || breakdownEnd > scopeEnd) {
      return void res.status(422).json({ error: "Breakdown dates must stay inside the selected scope date window." });
    }
    const breakdown = await prisma.trainingBreakdown.create({
      data: {
        projectId,
        trainingProviderId: training.trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        batchId: effectiveBatchId,
        breakStartDate: new Date(parsed.data.breakStartDate),
        breakEndDate: new Date(parsed.data.breakEndDate),
        reason: parsed.data.reason.trim(),
        status: "requested",
        requestedByUserId: req.auth!.userId,
      },
      select: { id: true },
    });
    await audit({
      projectId,
      trainingId,
      action: "training_breakdown_requested",
      sourceType: "training_breakdown",
      sourceRef: breakdown.id.toString(),
      payloadRaw: JSON.stringify(parsed.data),
      actorUserId: req.auth!.userId,
    });
    res.status(201).json({ item: { id: asId(breakdown.id) } });
  },
);

router.post(
  "/projects/:projectId/trainings/:trainingId/breakdowns/:breakdownId/decision",
  requirePermission("approve:training-breakdowns", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const trainingId = BigInt(req.params.trainingId);
    const breakdownId = BigInt(req.params.breakdownId);
    const parsed = z.object({ decision: z.enum(["approved", "rejected"]) }).safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const row = await prisma.trainingBreakdown.findFirst({ where: { id: breakdownId, projectId, trainingId } });
    if (!row) return void res.status(404).json({ error: "Breakdown request not found." });
    let updated: { id: bigint; status: string };
    if (parsed.data.decision === "approved") {
      const extensionDays = diffDaysInclusive(row.breakStartDate, row.breakEndDate);
      updated = await prisma.$transaction(async (tx) => {
        async function alignTrainingEndFromCohortMax() {
          const cohortEnds = await tx.trainingCohort.findMany({
            where: { projectId, trainingId },
            select: { endDate: true },
          });
          if (cohortEnds.length === 0) return;
          const maxC = cohortEnds.reduce<Date>((m, r) => (r.endDate.getTime() > m.getTime() ? r.endDate : m), cohortEnds[0]!.endDate);
          await tx.training.update({
            where: { id: trainingId },
            data: { endDate: maxC },
          });
        }

        if (row.batchId) {
          const batch = await tx.trainingBatch.findUnique({
            where: { id: row.batchId },
            select: { endDate: true, cohortId: true },
          });
          if (!batch) throw new Error("Batch not found while applying breakdown extension.");
          const newBatchEnd = new Date(batch.endDate);
          newBatchEnd.setUTCDate(newBatchEnd.getUTCDate() + extensionDays);
          await tx.trainingBatch.update({
            where: { id: row.batchId },
            data: { endDate: newBatchEnd },
          });
          const cohortBatchEnds = await tx.trainingBatch.findMany({
            where: { projectId, trainingId, cohortId: batch.cohortId },
            select: { endDate: true },
          });
          const maxBatchEnd = cohortBatchEnds.reduce<Date>((m, r) => (r.endDate.getTime() > m.getTime() ? r.endDate : m), newBatchEnd);
          await tx.trainingCohort.update({
            where: { id: batch.cohortId },
            data: { endDate: maxBatchEnd },
          });
          await alignTrainingEndFromCohortMax();
        } else if (row.cohortId) {
          const cohort = await tx.trainingCohort.findUnique({
            where: { id: row.cohortId },
            select: { endDate: true },
          });
          if (!cohort) throw new Error("Cohort not found while applying breakdown extension.");
          const newEndDate = new Date(cohort.endDate);
          newEndDate.setUTCDate(newEndDate.getUTCDate() + extensionDays);
          await tx.trainingCohort.update({
            where: { id: row.cohortId },
            data: { endDate: newEndDate },
          });
          const batchesInCohort = await tx.trainingBatch.findMany({
            where: { cohortId: row.cohortId },
            select: { id: true, endDate: true },
          });
          for (const b of batchesInCohort) {
            const nb = new Date(b.endDate);
            nb.setUTCDate(nb.getUTCDate() + extensionDays);
            await tx.trainingBatch.update({ where: { id: b.id }, data: { endDate: nb } });
          }
          await alignTrainingEndFromCohortMax();
        } else {
          const training = await tx.training.findUnique({
            where: { id: row.trainingId },
            select: { endDate: true },
          });
          if (!training) throw new Error("Training not found while applying breakdown extension.");
          const newTrainingEndDate = new Date(training.endDate);
          newTrainingEndDate.setUTCDate(newTrainingEndDate.getUTCDate() + extensionDays);
          await tx.training.update({
            where: { id: row.trainingId },
            data: { endDate: newTrainingEndDate },
          });
          const cohorts = await tx.trainingCohort.findMany({
            where: { projectId, trainingId, trainingProviderId: row.trainingProviderId },
            select: { id: true, endDate: true },
          });
          for (const c of cohorts) {
            const newCohortEndDate = new Date(c.endDate);
            newCohortEndDate.setUTCDate(newCohortEndDate.getUTCDate() + extensionDays);
            await tx.trainingCohort.update({
              where: { id: c.id },
              data: { endDate: newCohortEndDate },
            });
          }
          const batchesAll = await tx.trainingBatch.findMany({
            where: { projectId, trainingId, trainingProviderId: row.trainingProviderId },
            select: { id: true, endDate: true },
          });
          for (const b of batchesAll) {
            const nb = new Date(b.endDate);
            nb.setUTCDate(nb.getUTCDate() + extensionDays);
            await tx.trainingBatch.update({ where: { id: b.id }, data: { endDate: nb } });
          }
          await alignTrainingEndFromCohortMax();
        }
        return tx.trainingBreakdown.update({
          where: { id: breakdownId },
          data: {
            status: "approved",
            approvedByUserId: req.auth!.userId,
            approvedAt: new Date(),
          },
          select: { id: true, status: true },
        });
      });
    } else {
      updated = await prisma.trainingBreakdown.update({
        where: { id: breakdownId },
        data: {
          status: "rejected",
          approvedByUserId: null,
          approvedAt: null,
        },
        select: { id: true, status: true },
      });
    }
    await audit({
      projectId,
      trainingId,
      cohortId: row.cohortId,
      batchId: row.batchId,
      action: "training_breakdown_decided",
      sourceType: "training_breakdown",
      sourceRef: breakdownId.toString(),
      payloadRaw: JSON.stringify({ decision: parsed.data.decision }),
      meta:
        parsed.data.decision === "approved"
          ? {
              extensionDays: diffDaysInclusive(row.breakStartDate, row.breakEndDate),
              scope: row.batchId ? "batch" : row.cohortId ? "cohort" : "training",
            }
          : undefined,
      actorUserId: req.auth!.userId,
    });
    res.json({ item: { id: asId(updated.id), status: updated.status } });
  },
);

export default router;
