import path from "node:path";
import fs from "node:fs";
import { checkPlacement, PLACEMENT, PLACEMENT_META_KEYS } from "../services/placementRules.js";
import { Router, type Response } from "express";
import multer from "multer";
import { z } from "zod";
import { prisma } from "../prisma.js";
import type { Prisma } from "@prisma/client";
import { requireAuth, type AuthedRequest } from "../middleware/auth.js";
import { requirePermission } from "../middleware/permissions.js";
import { env } from "../env.js";
import { buildIndicatorKpiPayload } from "../services/indicatorKpis.js";
import { writeAuditEvent } from "../services/auditEventService.js";
import {
  OUTCOME_TEMPLATE_DEFS,
  buildOutcomeTemplateCsvBody,
  isTpOutcomeCsvReportType,
  TP_OUTCOME_UPLOAD_ORDER,
} from "../outcomeTemplateCatalog.js";
import { getOutcomeTemplatesForProject } from "../outcomeRosterReportLinks.js";
import {
  hasProjectAccess as hasProjectAccessPolicy,
  resolveProjectScope as resolveProjectScopePolicy,
  assertTpAssigned,
} from "../services/scopePolicy.js";
import {
  OBSOLETE_INDICATOR_VARIABLE_CODES,
  OBSOLETE_PROJECT_INDICATOR_CODES,
  SEED_ACTIVITIES,
  SEED_INDICATORS,
  SEED_VARIABLES,
} from "../performanceSeedCatalog.js";
import { scheduledSessionDates, sessionDateKey, type TrainingDateRange } from "../services/attendanceCalendar.js";
import { computeAttendanceCoverageForTrainingScope } from "../services/attendanceCoverageSlots.js";
import { computeDropoutProjections, summarizeReasonShares } from "../services/dropoutProtocol.js";
import { findSystemFinalDropoutViolations, systemFinalDropoutRejection } from "../services/dropoutPolicy.js";
import {
  buildDropoutProjectionApiSummary,
  enrichDropoutProjectionsWithKpiBuffer,
} from "../services/dropoutKpiBuffer.js";
import { contractTargetsByTp, registeredTraineesByTp } from "../services/providerContract.js";
import { trackedRosterRoleFilter } from "../services/traineeRoster.js";
import { resolveCohortIdForTrainingDelivery } from "../services/trainingScopeGuards.js";
import { multerFileSizeLimit } from "../uploadLimits.js";

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

/** Match plain outcome type or stage-suffixed keys (e.g. dropout:final). */
function traineePositiveSetHas(positives: Set<string>, outcomeType: string): boolean {
  if (positives.has(outcomeType)) return true;
  return [...positives].some((p) => p.startsWith(`${outcomeType}:`));
}

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);
}

const activityEvidenceStorage = multer.diskStorage({
  destination: (req, _file, cb) => {
    const projectId = String((req as AuthedRequest).params.projectId ?? "unknown");
    const dir = path.join(env.uploadRoot, "activity-evidence", projectId);
    fs.mkdirSync(dir, { recursive: true });
    cb(null, dir);
  },
  filename: (_req, file, cb) => {
    const safe = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}-${file.originalname.replace(/[^\w.\-()+]/g, "_")}`;
    cb(null, safe.slice(0, 200));
  },
});
const activityEvidenceMulter = multer({
  storage: activityEvidenceStorage,
  limits: multerFileSizeLimit,
});

const outcomeCsvUpload = multer({
  storage: multer.memoryStorage(),
  limits: multerFileSizeLimit,
});

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

// scope helpers moved to services/scopePolicy.ts

async function writeSubmissionEvent(args: {
  projectId: bigint;
  trainingProviderId?: bigint | null;
  trainingId?: bigint | null;
  cohortId?: bigint | null;
  module: string;
  action: string;
  sourceType?: string | null;
  sourceRef?: string | null;
  payloadRaw?: string | null;
  actorUserId?: bigint | null;
  meta?: Prisma.InputJsonValue;
}) {
  await writeAuditEvent({
    projectId: args.projectId,
    trainingProviderId: args.trainingProviderId ?? null,
    trainingId: args.trainingId ?? null,
    cohortId: args.cohortId ?? null,
    module: args.module as any,
    action: args.action,
    sourceType: args.sourceType ?? null,
    sourceRef: args.sourceRef ?? null,
    payloadRaw: args.payloadRaw ?? null,
    actorUserId: args.actorUserId ?? null,
    meta: args.meta,
  });
}

function indicatorSnapshot(i: {
  id: bigint;
  code: string;
  name: string;
  description: string | null;
  unit: string;
  computationMode: string;
  claimMode: string;
  verificationMode: string | null;
  thresholdValue: Prisma.Decimal | null;
  protocolOrder: number;
  monitoringNumeratorVariable: string | null;
  monitoringDenominatorVariable: string | null;
  verificationNumeratorVariable: string | null;
  verificationDenominatorVariable: string | null;
  cohortFilter: Prisma.JsonValue | null;
  definitionVersion: number;
  isLocked: boolean;
  isActive: boolean;
}) {
  return {
    id: i.id.toString(),
    code: i.code,
    name: i.name,
    description: i.description,
    unit: i.unit,
    computationMode: i.computationMode,
    claimMode: i.claimMode,
    verificationMode: i.verificationMode,
    thresholdValue: i.thresholdValue != null ? String(i.thresholdValue) : null,
    protocolOrder: i.protocolOrder,
    monitoringNumeratorVariable: i.monitoringNumeratorVariable,
    monitoringDenominatorVariable: i.monitoringDenominatorVariable,
    verificationNumeratorVariable: i.verificationNumeratorVariable,
    verificationDenominatorVariable: i.verificationDenominatorVariable,
    cohortFilter: i.cohortFilter,
    definitionVersion: i.definitionVersion,
    isLocked: i.isLocked,
    isActive: i.isActive,
  } as Prisma.InputJsonValue;
}

async function writeIndicatorVersion(args: {
  projectId: bigint;
  indicatorId: bigint;
  indicatorCode: string;
  versionNumber: number;
  action: "created" | "updated" | "locked" | "unlocked" | "deleted";
  snapshot: Prisma.InputJsonValue;
  changedByUserId: bigint;
}) {
  await prisma.projectIndicatorVersion.create({
    data: {
      projectId: args.projectId,
      indicatorId: args.indicatorId,
      indicatorCode: args.indicatorCode,
      versionNumber: args.versionNumber,
      action: args.action,
      snapshot: args.snapshot,
      changedByUserId: args.changedByUserId,
    },
  });
}

function outcomeResubScopeRef(
  trainingProviderId: bigint,
  trainingId: bigint,
  cohortId: bigint | null,
  reportType: string,
  stageKey?: string | null,
): string {
  return `${trainingProviderId.toString()}:${trainingId.toString()}:${cohortId ? cohortId.toString() : "0"}:${reportType}:${stageKey ?? "none"}`;
}

function dateOnlyUtc(d: Date): Date {
  return new Date(`${d.toISOString().slice(0, 10)}T00:00:00.000Z`);
}

async function getAttendanceCoverageForOutcomeScope(args: {
  projectId: bigint;
  trainingProviderId: bigint;
  trainingId: bigint;
  cohortId: bigint | null;
  batchId?: bigint | null;
}): Promise<{ expectedSlots: number; submittedRows: number }> {
  return computeAttendanceCoverageForTrainingScope({
    projectId: args.projectId,
    trainingProviderId: args.trainingProviderId,
    trainingId: args.trainingId,
    cohortId: args.cohortId,
    batchId: args.batchId ?? null,
  });
}

async function ensureDropoutSubmittedBeforeCompletion(args: {
  projectId: bigint;
  trainingProviderId: bigint;
  trainingId: bigint;
  cohortId: bigint | null;
  stageKey?: string | null;
}): Promise<boolean> {
  const row = await prisma.outcomeReportBatch.findFirst({
    where: {
      projectId: args.projectId,
      trainingProviderId: args.trainingProviderId,
      trainingId: args.trainingId,
      cohortId: args.cohortId,
      reportType: "dropout",
      status: "processed",
      ...(args.stageKey ? { meta: { path: "$.stageKey", equals: args.stageKey } as Prisma.JsonFilter } : {}),
    },
    select: { id: true },
  });
  return Boolean(row);
}

async function enforceActivitySubmissionWindow(args: {
  projectId: bigint;
  activityId: bigint;
  submissionScope: "provider" | "delivery";
  trainingId?: bigint | null;
  cohortId?: bigint | null;
  batchId?: bigint | null;
  now: Date;
}): Promise<
  | { ok: true; startDate: Date | null; endDate: Date | null; endDateEffective: Date | null; graceDaysAfterEnd: number }
  | { ok: false; status: 422; message: string }
> {
  if (args.submissionScope === "provider") {
    return {
      ok: true,
      startDate: null,
      endDate: null,
      endDateEffective: null,
      graceDaysAfterEnd: 0,
    };
  }
  if (!args.trainingId) {
    return { ok: false, status: 422, message: "trainingId is required for delivery-scoped activities." };
  }
  const trainingForRule = await prisma.training.findUnique({
    where: { id: args.trainingId },
    select: { trainingDurationId: true },
  });
  const scopedRule =
    trainingForRule?.trainingDurationId != null
      ? await (prisma.projectActivityRule as any).findFirst({
          where: {
            projectId: args.projectId,
            projectActivityId: args.activityId,
            trainingDurationId: trainingForRule.trainingDurationId,
            isActive: true,
          },
          orderBy: { id: "desc" },
        })
      : null;
  const rule = scopedRule;
  if (!rule) {
    return { ok: false, status: 422, message: "No duration-specific activity rule is configured for this training duration." };
  }
  let anchorTypeResolved: string = rule.anchorType;
  if (
    (anchorTypeResolved === "cohort_start" || anchorTypeResolved === "cohort_anchor") &&
    !args.cohortId
  ) {
    anchorTypeResolved = anchorTypeResolved === "cohort_anchor" ? "training_anchor" : "training_start";
  }
  if ((anchorTypeResolved === "batch_start" || anchorTypeResolved === "batch_anchor") && !args.batchId) {
    anchorTypeResolved =
      args.cohortId != null
        ? anchorTypeResolved === "batch_anchor"
          ? "cohort_anchor"
          : "cohort_start"
        : anchorTypeResolved === "batch_anchor"
          ? "training_anchor"
          : "training_start";
  }

  const today = dateOnlyUtc(args.now);
  const openOffsetDays = rule.openOffsetDays;
  const endOffsetDays = rule.endOffsetDays;
  let anchorDate: Date | null = null;
  if (anchorTypeResolved === "batch_start" || anchorTypeResolved === "batch_anchor") {
    const batch = await prisma.trainingBatch.findFirst({
      where: {
        id: args.batchId!,
        projectId: args.projectId,
        trainingId: args.trainingId,
        ...(args.cohortId != null ? { cohortId: args.cohortId } : {}),
      },
      select: { timelineAnchorDate: true, startDate: true },
    });
    anchorDate =
      anchorTypeResolved === "batch_anchor"
        ? batch?.timelineAnchorDate ?? batch?.startDate ?? null
        : batch?.startDate ?? batch?.timelineAnchorDate ?? null;
  } else if (anchorTypeResolved === "cohort_start" || anchorTypeResolved === "cohort_anchor") {
    const cohort = await prisma.trainingCohort.findUnique({
      where: { id: args.cohortId! },
      select: { timelineAnchorDate: true, startDate: true },
    });
    anchorDate =
      anchorTypeResolved === "cohort_anchor"
        ? cohort?.timelineAnchorDate ?? cohort?.startDate ?? null
        : cohort?.startDate ?? cohort?.timelineAnchorDate ?? null;
  } else {
    const training = await prisma.training.findUnique({
      where: { id: args.trainingId },
      select: { timelineAnchorDate: true, startDate: true },
    });
    anchorDate =
      anchorTypeResolved === "training_anchor"
        ? training?.timelineAnchorDate ?? training?.startDate ?? null
        : training?.startDate ?? training?.timelineAnchorDate ?? null;
  }
  const anchoredDate = (offset: number | null, fallback: Date | null) => {
    if (offset == null || !anchorDate) return fallback;
    const d = dateOnlyUtc(anchorDate);
    d.setUTCDate(d.getUTCDate() + offset);
    return d;
  };
  let start = anchoredDate(openOffsetDays, null);
  const endBase = anchoredDate(endOffsetDays, null);
  let end = endBase;
  let freezeBlocked = false;
  let freezeBlockedDate: Date | null = null;
  const breakdownOr: Array<
    | { cohortId: null; batchId: null }
    | { cohortId: bigint; batchId: null }
    | { batchId: bigint }
  > = [{ cohortId: null, batchId: null }];
  if (args.cohortId != null) breakdownOr.push({ cohortId: args.cohortId, batchId: null });
  if (args.batchId != null) breakdownOr.push({ batchId: args.batchId });

  const breakdowns = await prisma.trainingBreakdown.findMany({
    where: {
      projectId: args.projectId,
      trainingId: args.trainingId,
      status: "approved",
      OR: breakdownOr,
    },
    select: { breakStartDate: true, breakEndDate: true },
  });
  if (breakdowns.length > 0) {
    const diffInclusive = (a: Date, b: Date) =>
      Math.floor((dateOnlyUtc(b).getTime() - dateOnlyUtc(a).getTime()) / (24 * 60 * 60 * 1000)) + 1;

    type Interval = { s: Date; e: Date };
    const merged: Interval[] = [];
    const sorted = breakdowns
      .map((b) => ({ s: dateOnlyUtc(b.breakStartDate), e: dateOnlyUtc(b.breakEndDate) }))
      .sort((a, b) => a.s.getTime() - b.s.getTime());

    for (const it of sorted) {
      if (!merged.length) {
        merged.push({ s: it.s, e: it.e });
        continue;
      }
      const last = merged[merged.length - 1];
      // Intervals overlap or touch => merge. Using +1 day because dates are inclusive.
      const lastPlusOne = new Date(last.e);
      lastPlusOne.setUTCDate(lastPlusOne.getUTCDate() + 1);
      if (it.s <= lastPlusOne) {
        if (it.e > last.e) last.e = it.e;
      } else {
        merged.push({ s: it.s, e: it.e });
      }
    }

    const extensionDaysUpTo = (target: Date): number => {
      const t = dateOnlyUtc(target);
      let sum = 0;
      for (const it of merged) {
        if (t < it.s) break;
        if (t >= it.e) sum += Math.max(0, diffInclusive(it.s, it.e));
        else sum += Math.max(0, diffInclusive(it.s, t));
      }
      return sum;
    };

    // Freeze if "today" falls inside any approved breakdown window.
    for (const it of merged) {
      if (today >= it.s && today <= it.e) {
        freezeBlocked = true;
        freezeBlockedDate = it.e;
        break;
      }
    }

    // Offsets are applied on an extended timeline where breakdown days effectively add calendar days.
    // We therefore shift each computed date by only the breakdown days that occur BEFORE that date.
    const extStart = start ? extensionDaysUpTo(start) : 0;
    const extEnd = endBase ? extensionDaysUpTo(endBase) : 0;

    if (extStart > 0 && start) {
      start = new Date(start);
      start.setUTCDate(start.getUTCDate() + extStart);
    }
    if (extEnd > 0 && endBase) {
      end = new Date(endBase);
      end.setUTCDate(end.getUTCDate() + extEnd);
    }
  }
  if (freezeBlocked) {
    return {
      ok: false,
      status: 422,
      message: `Submission is paused during approved breakdown period${freezeBlockedDate ? ` (until ${freezeBlockedDate.toISOString().slice(0, 10)})` : ""}.`,
    };
  }
  const graceDaysAfterEnd = Math.max(0, Math.floor(rule.graceDaysAfterEnd ?? 0));
  if (start && today < start) {
    return { ok: false, status: 422, message: `Submission window opens on ${start.toISOString().slice(0, 10)}.` };
  }
  if (end && today > end) {
    if (graceDaysAfterEnd <= 0) {
      return { ok: false, status: 422, message: `Submission window closed on ${end.toISOString().slice(0, 10)}.` };
    }
    const endWithGrace = new Date(end);
    endWithGrace.setUTCDate(endWithGrace.getUTCDate() + graceDaysAfterEnd);
    if (today > endWithGrace) {
      return {
        ok: false,
        status: 422,
        message: `Submission window closed on ${endWithGrace.toISOString().slice(0, 10)} (includes grace period).`,
      };
    }
  }
  const endEffective =
    end && graceDaysAfterEnd > 0
      ? (() => {
          const d = dateOnlyUtc(end);
          d.setUTCDate(d.getUTCDate() + graceDaysAfterEnd);
          return d;
        })()
      : (end ?? null);
  return {
    ok: true,
    startDate: start ?? null,
    endDate: end ?? null,
    endDateEffective: endEffective,
    graceDaysAfterEnd,
  };
}

type ResubmissionGate =
  | { allowed: true; requestEventId: bigint | null }
  | { allowed: false; status: "no_request" | "pending" | "rejected" | "already_used"; message: string };

async function evaluateOutcomeResubmissionGate(args: {
  projectId: bigint;
  trainingProviderId: bigint;
  trainingId: bigint;
  cohortId: bigint | null;
  reportType: string;
  stageKey?: string | null;
}): Promise<ResubmissionGate> {
  const scopeRef = outcomeResubScopeRef(args.trainingProviderId, args.trainingId, args.cohortId, args.reportType, args.stageKey ?? null);
  const latestRequest = await prisma.submissionEvent.findFirst({
    where: {
      projectId: args.projectId,
      module: "outcomes",
      action: "resubmission_requested",
      sourceRef: scopeRef,
    },
    orderBy: { id: "desc" },
    select: { id: true },
  });
  if (!latestRequest) {
    return {
      allowed: false,
      status: "no_request",
      message: "A processed report already exists for this scope. Submit a resubmission request first.",
    };
  }
  const latestDecision = await prisma.submissionEvent.findFirst({
    where: {
      projectId: args.projectId,
      module: "outcomes",
      action: { in: ["resubmission_approved", "resubmission_rejected"] },
      sourceRef: latestRequest.id.toString(),
    },
    orderBy: { id: "desc" },
    select: { id: true, action: true },
  });
  if (!latestDecision) {
    return {
      allowed: false,
      status: "pending",
      message: "A resubmission request is pending approval for this scope.",
    };
  }
  if (latestDecision.action === "resubmission_rejected") {
    return {
      allowed: false,
      status: "rejected",
      message: "The latest resubmission request for this scope was rejected.",
    };
  }
  const consumed = await prisma.submissionEvent.findFirst({
    where: {
      projectId: args.projectId,
      module: "outcomes",
      action: "resubmission_consumed",
      sourceRef: latestRequest.id.toString(),
    },
    orderBy: { id: "desc" },
    select: { id: true },
  });
  if (consumed) {
    return {
      allowed: false,
      status: "already_used",
      message: "The approved resubmission request was already used. Submit a new request for another resubmission.",
    };
  }
  return { allowed: true, requestEventId: latestRequest.id };
}

// ---------- Indicator variables (global catalogue) ----------
router.get("/indicator-variables", requirePermission("view:indicators"), async (_req, res) => {
  const items = await prisma.indicatorVariable.findMany({
    where: { isActive: true },
    orderBy: { name: "asc" },
  });
  res.json({
    items: items.map((v) => ({
      id: asId(v.id),
      code: v.code,
      name: v.name,
      description: v.description,
      querySpec: v.querySpec,
    })),
  });
});

router.post("/indicator-variables", requirePermission("manage:indicators"), async (req, res) => {
  const parsed = z
    .object({
      code: z.string().min(1).max(100),
      name: z.string().min(1),
      description: z.string().optional(),
      querySpec: z.record(z.unknown()).optional(),
      isActive: z.boolean().optional(),
    })
    .safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  const created = await prisma.indicatorVariable.create({
    data: {
      code: parsed.data.code.trim(),
      name: parsed.data.name.trim(),
      description: parsed.data.description?.trim() ?? null,
      querySpec: (parsed.data.querySpec ?? undefined) as Prisma.InputJsonValue | undefined,
      isActive: parsed.data.isActive ?? true,
    },
  });
  res.status(201).json({ item: { id: asId(created.id), code: created.code } });
});

// ---------- Project indicators ----------
router.get(
  "/projects/:projectId/indicators",
  requirePermission("view:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const items = await prisma.projectIndicator.findMany({
      where: { projectId },
      orderBy: [{ protocolOrder: "asc" }, { code: "asc" }],
      include: { stages: { where: { isActive: true }, orderBy: [{ sortOrder: "asc" }, { id: "asc" }] } },
    });
    res.json({
      items: items.map((i) => ({
        id: asId(i.id),
        code: i.code,
        name: i.name,
        description: i.description,
        unit: i.unit,
        computationMode: i.computationMode,
        claimMode: i.claimMode,
        verificationMode: i.verificationMode,
        thresholdValue: i.thresholdValue != null ? String(i.thresholdValue) : null,
        protocolOrder: i.protocolOrder,
        monitoringNumeratorVariable: i.monitoringNumeratorVariable,
        monitoringDenominatorVariable: i.monitoringDenominatorVariable,
        verificationNumeratorVariable: i.verificationNumeratorVariable,
        verificationDenominatorVariable: i.verificationDenominatorVariable,
        cohortFilter: i.cohortFilter,
        definitionVersion: i.definitionVersion,
        isLocked: i.isLocked,
        isActive: i.isActive,
        stages: i.stages.map((s) => ({
          id: asId(s.id),
          stageKey: s.stageKey,
          label: s.label,
          offsetDaysFromReference: s.offsetDaysFromReference,
          isFinalStage: s.isFinalStage,
          sortOrder: s.sortOrder,
        })),
      })),
    });
  },
);

router.get(
  "/projects/:projectId/indicators/:indicatorId/versions",
  requirePermission("view:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const rows = await prisma.projectIndicatorVersion.findMany({
      where: { projectId, indicatorId },
      orderBy: { id: "desc" },
      take: 200,
    });
    res.json({
      items: rows.map((r) => ({
        id: asId(r.id),
        indicatorId: asId(r.indicatorId),
        indicatorCode: r.indicatorCode,
        versionNumber: r.versionNumber,
        action: r.action,
        snapshot: r.snapshot,
        changedByUserId: r.changedByUserId ? asId(r.changedByUserId) : null,
        createdAt: r.createdAt.toISOString(),
      })),
    });
  },
);

router.get(
  "/projects/:projectId/indicators/:indicatorId/stages",
  requirePermission("view:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const rows = await prisma.projectIndicatorStage.findMany({
      where: { projectId, indicatorId, isActive: true },
      orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
    });
    res.json({
      items: rows.map((r) => ({
        id: asId(r.id),
        indicatorId: asId(r.indicatorId),
        stageKey: r.stageKey,
        label: r.label,
        offsetDaysFromReference: r.offsetDaysFromReference,
        isFinalStage: r.isFinalStage,
        sortOrder: r.sortOrder,
        isActive: r.isActive,
      })),
    });
  },
);

const indicatorStageBody = z.object({
  stageKey: z.string().min(1).max(40).optional(),
  label: z.string().min(1).max(120),
  offsetDaysFromReference: z.number().int().min(0).max(3650).optional(),
  isFinalStage: z.boolean().optional(),
  sortOrder: z.number().int().min(0).max(999).optional(),
  isActive: z.boolean().optional(),
});

router.post(
  "/projects/:projectId/indicators/:indicatorId/stages",
  requirePermission("manage:verification-stages", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = indicatorStageBody.safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const current = await prisma.projectIndicatorStage.findMany({
      where: { projectId, indicatorId },
      orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
      select: { sortOrder: true, stageKey: true },
    });
    const autoOrder = (current.at(-1)?.sortOrder ?? 0) + 10;
    let stageKey = parsed.data.stageKey?.trim() || `stage_${current.length + 1}`;
    const existingKeys = new Set(current.map((s) => s.stageKey));
    while (existingKeys.has(stageKey)) {
      stageKey = `stage_${Date.now()}`;
    }
    const row = await prisma.projectIndicatorStage.create({
      data: {
        projectId,
        indicatorId,
        stageKey,
        label: parsed.data.label.trim(),
        offsetDaysFromReference: parsed.data.offsetDaysFromReference ?? 0,
        isFinalStage: parsed.data.isFinalStage ?? false,
        sortOrder: parsed.data.sortOrder ?? autoOrder,
        isActive: parsed.data.isActive ?? true,
      },
      select: { id: true },
    });
    if (parsed.data.isFinalStage === true) {
      await prisma.projectIndicatorStage.updateMany({
        where: { projectId, indicatorId, id: { not: row.id } },
        data: { isFinalStage: false },
      });
    }
    res.status(201).json({ item: { id: asId(row.id) } });
  },
);

router.put(
  "/projects/:projectId/indicators/:indicatorId/stages/:stageId",
  requirePermission("manage:verification-stages", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    const stageId = BigInt(req.params.stageId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = indicatorStageBody.partial().safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const ex = await prisma.projectIndicatorStage.findFirst({ where: { id: stageId, projectId, indicatorId }, select: { id: true } });
    if (!ex) return void res.status(404).json({ error: "Stage not found." });
    await prisma.projectIndicatorStage.update({
      where: { id: stageId },
      data: {
        ...(parsed.data.stageKey !== undefined ? { stageKey: parsed.data.stageKey.trim() } : {}),
        ...(parsed.data.label !== undefined ? { label: parsed.data.label.trim() } : {}),
        ...(parsed.data.offsetDaysFromReference !== undefined ? { offsetDaysFromReference: parsed.data.offsetDaysFromReference } : {}),
        ...(parsed.data.isFinalStage !== undefined ? { isFinalStage: parsed.data.isFinalStage } : {}),
        ...(parsed.data.sortOrder !== undefined ? { sortOrder: parsed.data.sortOrder } : {}),
        ...(parsed.data.isActive !== undefined ? { isActive: parsed.data.isActive } : {}),
      },
    });
    if (parsed.data.isFinalStage === true) {
      await prisma.projectIndicatorStage.updateMany({
        where: { projectId, indicatorId, id: { not: stageId } },
        data: { isFinalStage: false },
      });
    }
    res.json({ ok: true });
  },
);

router.delete(
  "/projects/:projectId/indicators/:indicatorId/stages/:stageId",
  requirePermission("manage:verification-stages", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    const stageId = BigInt(req.params.stageId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const ex = await prisma.projectIndicatorStage.findFirst({ where: { id: stageId, projectId, indicatorId }, select: { id: true } });
    if (!ex) return void res.status(404).json({ error: "Stage not found." });
    await prisma.projectIndicatorStage.delete({ where: { id: stageId } });
    res.json({ ok: true });
  },
);

const indicatorBody = z.object({
  code: z.string().min(1).max(100),
  name: z.string().min(1),
  description: z.string().optional(),
  unit: z.string().max(20).optional(),
  computationMode: z.enum(["count", "percentage"]),
  claimMode: z.enum(["system_computed", "trainee_roster", "tp_aggregate", "activity_evidence"]),
  verificationMode: z.enum(["sampling", "full_review", "system", "none"]).optional().nullable(),
  thresholdValue: z.number().optional().nullable(),
  protocolOrder: z.number().int().optional(),
  monitoringNumeratorVariable: z.string().max(100).optional().nullable(),
  monitoringDenominatorVariable: z.string().max(100).optional().nullable(),
  verificationNumeratorVariable: z.string().max(100).optional().nullable(),
  verificationDenominatorVariable: z.string().max(100).optional().nullable(),
  cohortFilter: z.array(z.record(z.unknown())).optional().nullable(),
  isLocked: z.boolean().optional(),
  isActive: z.boolean().optional(),
});

router.post(
  "/projects/:projectId/indicators",
  requirePermission("manage:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = indicatorBody.safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const d = parsed.data;
    try {
      const created = await prisma.projectIndicator.create({
        data: {
          projectId,
          code: d.code.trim(),
          name: d.name.trim(),
          description: d.description?.trim() ?? null,
          unit: d.unit ?? "%",
          computationMode: d.computationMode,
          claimMode: d.claimMode,
          verificationMode: d.verificationMode ?? null,
          thresholdValue: d.thresholdValue ?? null,
          protocolOrder: d.protocolOrder ?? 0,
          monitoringNumeratorVariable: d.monitoringNumeratorVariable ?? null,
          monitoringDenominatorVariable: d.monitoringDenominatorVariable ?? null,
          verificationNumeratorVariable: d.verificationNumeratorVariable ?? null,
          verificationDenominatorVariable: d.verificationDenominatorVariable ?? null,
          cohortFilter: (d.cohortFilter ?? undefined) as Prisma.InputJsonValue | undefined,
          isLocked: d.isLocked ?? false,
          isActive: d.isActive ?? true,
        },
      });
      await writeIndicatorVersion({
        projectId,
        indicatorId: created.id,
        indicatorCode: created.code,
        versionNumber: created.definitionVersion,
        action: "created",
        snapshot: indicatorSnapshot(created),
        changedByUserId: req.auth!.userId,
      });
      await writeSubmissionEvent({
        projectId,
        module: "indicators",
        action: "indicator_created",
        sourceType: "indicator",
        sourceRef: created.id.toString(),
        payloadRaw: JSON.stringify(indicatorSnapshot(created)),
        actorUserId: req.auth!.userId,
      });
      res.status(201).json({ item: { id: asId(created.id) } });
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Create failed";
      res.status(400).json({ error: msg });
    }
  },
);

router.put(
  "/projects/:projectId/indicators/:indicatorId",
  requirePermission("manage:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const existing = await prisma.projectIndicator.findFirst({ where: { id: indicatorId, projectId } });
    if (!existing) return void res.status(404).json({ error: "Not found." });
    if (existing.isLocked && !req.body?.unlockAndVersionBump) {
      return void res.status(422).json({ error: "Indicator is locked. Send unlockAndVersionBump with bumped definitionVersion to edit." });
    }
    const parsed = indicatorBody.partial().safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const d = parsed.data;
    const data: Prisma.ProjectIndicatorUpdateInput = {};
    const oldLocked = existing.isLocked;
    if (d.name !== undefined) data.name = d.name.trim();
    if (d.description !== undefined) data.description = d.description?.trim() ?? null;
    if (d.unit !== undefined) data.unit = d.unit;
    if (d.computationMode !== undefined) data.computationMode = d.computationMode;
    if (d.claimMode !== undefined) data.claimMode = d.claimMode;
    if (d.verificationMode !== undefined) data.verificationMode = d.verificationMode;
    if (d.thresholdValue !== undefined) data.thresholdValue = d.thresholdValue;
    if (d.protocolOrder !== undefined) data.protocolOrder = d.protocolOrder;
    if (d.monitoringNumeratorVariable !== undefined) data.monitoringNumeratorVariable = d.monitoringNumeratorVariable;
    if (d.monitoringDenominatorVariable !== undefined) data.monitoringDenominatorVariable = d.monitoringDenominatorVariable;
    if (d.verificationNumeratorVariable !== undefined) data.verificationNumeratorVariable = d.verificationNumeratorVariable;
    if (d.verificationDenominatorVariable !== undefined) data.verificationDenominatorVariable = d.verificationDenominatorVariable;
    if (d.cohortFilter !== undefined) data.cohortFilter = d.cohortFilter as Prisma.InputJsonValue | undefined;
    if (d.isLocked !== undefined) data.isLocked = d.isLocked;
    if (d.isActive !== undefined) data.isActive = d.isActive;
    if (req.body?.unlockAndVersionBump && existing.isLocked) {
      data.definitionVersion = { increment: 1 };
      data.isLocked = false;
    }
    const updated = await prisma.projectIndicator.update({ where: { id: indicatorId }, data });
    await writeIndicatorVersion({
      projectId,
      indicatorId: updated.id,
      indicatorCode: updated.code,
      versionNumber: updated.definitionVersion,
      action:
        oldLocked && updated.isLocked === false
          ? "unlocked"
          : !oldLocked && updated.isLocked === true
            ? "locked"
            : "updated",
      snapshot: indicatorSnapshot(updated),
      changedByUserId: req.auth!.userId,
    });
    await writeSubmissionEvent({
      projectId,
      module: "indicators",
      action: oldLocked !== updated.isLocked ? "indicator_lock_state_changed" : "indicator_updated",
      sourceType: "indicator",
      sourceRef: updated.id.toString(),
      payloadRaw: JSON.stringify(indicatorSnapshot(updated)),
      actorUserId: req.auth!.userId,
    });
    res.json({ ok: true });
  },
);

router.delete(
  "/projects/:projectId/indicators/:indicatorId",
  requirePermission("manage:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const indicatorId = BigInt(req.params.indicatorId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const existing = await prisma.projectIndicator.findFirst({ where: { id: indicatorId, projectId } });
    if (!existing) return void res.status(404).json({ error: "Not found." });
    if (existing.isLocked) return void res.status(422).json({ error: "Locked indicators cannot be deleted." });
    await writeIndicatorVersion({
      projectId,
      indicatorId: existing.id,
      indicatorCode: existing.code,
      versionNumber: existing.definitionVersion,
      action: "deleted",
      snapshot: indicatorSnapshot(existing),
      changedByUserId: req.auth!.userId,
    });
    await writeSubmissionEvent({
      projectId,
      module: "indicators",
      action: "indicator_deleted",
      sourceType: "indicator",
      sourceRef: existing.id.toString(),
      payloadRaw: JSON.stringify(indicatorSnapshot(existing)),
      actorUserId: req.auth!.userId,
    });
    await prisma.projectIndicator.delete({ where: { id: indicatorId } });
    res.json({ ok: true });
  },
);

router.get(
  "/projects/:projectId/indicator-kpis",
  requirePermission("view:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const payload = await buildIndicatorKpiPayload(projectId);
    res.json(payload);
  },
);

router.get(
  "/projects/:projectId/submission-events",
  requirePermission("view:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const items = await prisma.submissionEvent.findMany({
      where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
      orderBy: { id: "desc" },
      take: 200,
    });
    res.json({
      items: items.map((e) => ({
        id: asId(e.id),
        module: e.module,
        action: e.action,
        trainingProviderId: e.trainingProviderId ? asId(e.trainingProviderId) : null,
        trainingId: e.trainingId ? asId(e.trainingId) : null,
        sourceType: e.sourceType,
        sourceRef: e.sourceRef,
        payloadHash: e.payloadHash,
        actorUserId: e.actorUserId ? asId(e.actorUserId) : null,
        createdAt: e.createdAt.toISOString(),
      })),
    });
  }
);

// ---------- Project activities ----------
router.get(
  "/projects/:projectId/activities",
  requirePermission("view:activities", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const providerScopedActivityIds =
      scope.providerId != null
        ? (
            await (prisma.projectActivityAssignment as any).findMany({
              where: { projectId, trainingProviderId: scope.providerId },
              select: { projectActivityId: true },
            })
          ).map((x: { projectActivityId: bigint }) => x.projectActivityId)
        : null;
    const items: any[] = await (prisma.projectActivity as any).findMany({
      where: {
        projectId,
        ...(scope.providerId != null
          ? { id: { in: providerScopedActivityIds && providerScopedActivityIds.length > 0 ? providerScopedActivityIds : [-1n] } }
          : {}),
      },
      orderBy: [{ sortOrder: "asc" }, { code: "asc" }],
      include: {
        rules: {
          include: { trainingDuration: { select: { id: true, label: true, months: true } } },
          orderBy: [{ trainingDurationId: "asc" }, { id: "asc" }],
        },
        assignments: { select: { trainingProviderId: true } } as any,
      },
    });
    res.json({
      items: items.map((a: any) => ({
        id: asId(a.id),
        code: a.code,
        name: a.name,
        description: a.description,
        submissionScope: ((a as unknown as { submissionScope?: string }).submissionScope ?? "delivery") as "provider" | "delivery",
        assignedProviderIds: ((a as unknown as { assignments?: Array<{ trainingProviderId: bigint }> }).assignments ?? []).map((x) =>
          x.trainingProviderId.toString(),
        ),
        sortOrder: a.sortOrder,
        isActive: a.isActive,
        rules: ((a as any).rules ?? []).map((r: any) => ({
          id: asId(r.id),
          trainingDurationId: r.trainingDurationId ? asId(r.trainingDurationId) : null,
          trainingDurationLabel: r.trainingDuration ? r.trainingDuration.label : null,
          trainingDurationMonths: r.trainingDuration ? r.trainingDuration.months : null,
          anchorType: r.anchorType,
          openOffsetDays: r.openOffsetDays ?? null,
          endOffsetDays: r.endOffsetDays ?? null,
          graceDaysAfterEnd: r.graceDaysAfterEnd ?? 0,
          isActive: r.isActive,
        })),
      })),
    });
  },
);

router.get(
  "/projects/:projectId/activities/:activityId/preview-window",
  requirePermission("view:activities", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const activityId = BigInt(req.params.activityId);
    const trainingId =
      typeof req.query.trainingId === "string" && /^\d+$/.test(req.query.trainingId) ? BigInt(req.query.trainingId) : null;
    const cohortId =
      typeof req.query.cohortId === "string" && /^\d+$/.test(req.query.cohortId) ? BigInt(req.query.cohortId) : null;
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const activity = await (prisma.projectActivity as any).findFirst({
      where: { id: activityId, projectId },
      select: { id: true, submissionScope: true },
    });
    if (!activity) return void res.status(404).json({ error: "Activity not found." });
    if (scope.providerId) {
      const assigned = await (prisma.projectActivityAssignment as any).findFirst({
        where: { projectId, projectActivityId: activityId, trainingProviderId: scope.providerId },
        select: { id: true },
      });
      if (!assigned) return void res.status(403).json({ error: "This activity is not assigned to your provider." });
    }
    let effectiveTrainingId: bigint | null = null;
    let effectiveCohortId: bigint | null = null;
    if (activity.submissionScope === "delivery") {
      if (!trainingId) return void res.status(400).json({ error: "trainingId is required for delivery-scoped activities." });
      const training = await prisma.training.findFirst({
        where: { id: trainingId, projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
        select: { id: true, trainingProviderId: true },
      });
      if (!training) return void res.status(404).json({ error: "Training not found." });
      effectiveTrainingId = training.id;
      try {
        effectiveCohortId = await resolveCohortIdForTrainingDelivery({
          prisma,
          projectId,
          trainingProviderId: training.trainingProviderId,
          trainingId: training.id,
          cohortId,
        });
      } catch (e: any) {
        return void res.status(e?.status ?? 400).json({ error: e?.message ?? "Invalid cohort." });
      }
    }
    const gate = await enforceActivitySubmissionWindow({
      projectId,
      activityId,
      submissionScope: activity.submissionScope as "provider" | "delivery",
      trainingId: effectiveTrainingId,
      cohortId: effectiveCohortId,
      now: new Date(),
    });
    if (!gate.ok) {
      return void res.status(gate.status).json({
        error: gate.message,
        item: {
          openDate: null,
          endDate: null,
          endDateEffective: null,
          graceDaysAfterEnd: 0,
          canSubmitNow: false,
        },
      });
    }
    const trainingForRule = effectiveTrainingId
      ? await prisma.training.findUnique({ where: { id: effectiveTrainingId }, select: { trainingDurationId: true } })
      : null;
    const scopedRule =
      trainingForRule?.trainingDurationId != null
        ? await (prisma.projectActivityRule as any).findFirst({
            where: {
              projectId,
              projectActivityId: activityId,
              trainingDurationId: trainingForRule.trainingDurationId,
              isActive: true,
            },
            select: { anchorType: true },
            orderBy: { id: "desc" },
          })
        : null;
    const rule = scopedRule;
    res.json({
      item: {
        anchorType: activity.submissionScope === "provider" ? "provider" : rule?.anchorType ?? null,
        openDate: gate.startDate ? gate.startDate.toISOString().slice(0, 10) : null,
        endDate: gate.endDate ? gate.endDate.toISOString().slice(0, 10) : null,
        endDateEffective: gate.endDateEffective ? gate.endDateEffective.toISOString().slice(0, 10) : null,
        graceDaysAfterEnd: gate.graceDaysAfterEnd,
        canSubmitNow: true,
      },
    });
  },
);

router.post(
  "/projects/:projectId/activities",
  requirePermission("manage:activities", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = z
      .object({
        code: z.string().min(1).max(64),
        name: z.string().min(1),
        description: z.string().optional(),
        submissionScope: z.enum(["provider", "delivery"]).optional(),
        assignedProviderIds: z.array(z.string()).optional(),
        assignToAllProviders: z.boolean().optional(),
        sortOrder: z.number().int().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 requestedAssignedProviderIds = (parsed.data.assignedProviderIds ?? [])
      .filter((v) => /^\d+$/.test(v))
      .map((v) => BigInt(v));
    let assignedProviderIds: bigint[] = [];
    if (scope.providerId) {
      assignedProviderIds = [scope.providerId];
    } else if (parsed.data.assignToAllProviders) {
      const allProviders = await prisma.trainingProvider.findMany({ where: { projectId }, select: { id: true } });
      assignedProviderIds = allProviders.map((p) => p.id);
    } else if (requestedAssignedProviderIds.length > 0) {
      const providers = await prisma.trainingProvider.findMany({
        where: { projectId, id: { in: requestedAssignedProviderIds } },
        select: { id: true },
      });
      assignedProviderIds = providers.map((p) => p.id);
    }
    const created = await (prisma.projectActivity as any).create({
      data: {
        projectId,
        createdByTrainingProviderId: scope.providerId ?? null,
        code: parsed.data.code.trim(),
        name: parsed.data.name.trim(),
        description: parsed.data.description?.trim() ?? null,
        submissionScope: parsed.data.submissionScope ?? "delivery",
        sortOrder: parsed.data.sortOrder ?? 0,
      },
    });
    if (assignedProviderIds.length > 0) {
      await (prisma.projectActivityAssignment as any).createMany({
        data: assignedProviderIds.map((providerId) => ({
          projectId,
          projectActivityId: created.id,
          trainingProviderId: providerId,
        })),
      });
    }
    res.status(201).json({ item: { id: asId(created.id) } });
  },
);

router.put(
  "/projects/:projectId/activities/:activityId",
  requirePermission("manage:activities", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const activityId = BigInt(req.params.activityId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = z
      .object({
        code: z.string().min(1).max(64),
        name: z.string().min(1),
        description: z.string().optional(),
        submissionScope: z.enum(["provider", "delivery"]),
        assignedProviderIds: z.array(z.string()).optional(),
        assignToAllProviders: z.boolean().optional(),
        sortOrder: z.number().int().optional(),
        isActive: 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);
    const existing = await (prisma.projectActivity as any).findFirst({
      where: { id: activityId, projectId },
      select: { id: true, createdByTrainingProviderId: true },
    });
    if (!existing) return void res.status(404).json({ error: "Activity not found." });
    if (scope.providerId && existing.createdByTrainingProviderId?.toString() !== scope.providerId.toString()) {
      return void res.status(403).json({ error: "TP can only edit activities created by their own provider." });
    }

    const requestedAssignedProviderIds = (parsed.data.assignedProviderIds ?? [])
      .filter((v) => /^\d+$/.test(v))
      .map((v) => BigInt(v));
    let assignedProviderIds: bigint[] = [];
    if (scope.providerId) {
      assignedProviderIds = [scope.providerId];
    } else if (parsed.data.assignToAllProviders) {
      const allProviders = await prisma.trainingProvider.findMany({ where: { projectId }, select: { id: true } });
      assignedProviderIds = allProviders.map((p) => p.id);
    } else if (requestedAssignedProviderIds.length > 0) {
      const providers = await prisma.trainingProvider.findMany({
        where: { projectId, id: { in: requestedAssignedProviderIds } },
        select: { id: true },
      });
      assignedProviderIds = providers.map((p) => p.id);
    }
    if (assignedProviderIds.length === 0 && scope.providerId) assignedProviderIds = [scope.providerId];

    await prisma.$transaction(async (tx) => {
      await (tx.projectActivity as any).update({
        where: { id: activityId },
        data: {
          code: parsed.data.code.trim(),
          name: parsed.data.name.trim(),
          description: parsed.data.description?.trim() ?? null,
          submissionScope: parsed.data.submissionScope,
          sortOrder: parsed.data.sortOrder ?? 0,
          ...(typeof parsed.data.isActive === "boolean" ? { isActive: parsed.data.isActive } : {}),
        },
      });
      await (tx.projectActivityAssignment as any).deleteMany({ where: { projectId, projectActivityId: activityId } });
      if (assignedProviderIds.length > 0) {
        await (tx.projectActivityAssignment as any).createMany({
          data: assignedProviderIds.map((providerId) => ({
            projectId,
            projectActivityId: activityId,
            trainingProviderId: providerId,
          })),
        });
      }
    });
    res.json({ item: { id: activityId.toString() } });
  },
);

router.put(
  "/projects/:projectId/activity-windows",
  requirePermission("manage:activity-windows", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = z
      .object({
        ruleId: z.string().optional(),
        projectActivityId: z.string(),
        trainingDurationId: z.string(),
        anchorType: z
          .enum([
            "training_start",
            "training_anchor",
            "cohort_start",
            "cohort_anchor",
            "batch_start",
            "batch_anchor",
          ])
          .optional(),
        openOffsetDays: z.number().int().min(-365).max(365).optional().nullable(),
        endOffsetDays: z.number().int().min(-365).max(365).optional().nullable(),
        graceDaysAfterEnd: z.number().int().min(0).max(365).optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const activityId = BigInt(parsed.data.projectActivityId);
    if (!/^\d+$/.test(parsed.data.trainingDurationId)) {
      return void res.status(400).json({ error: "trainingDurationId is required and must be numeric." });
    }
    const trainingDurationId = BigInt(parsed.data.trainingDurationId);
    const act = await (prisma.projectActivity as any).findFirst({ where: { id: activityId, projectId }, select: { id: true, submissionScope: true } });
    if (!act) return void res.status(404).json({ error: "Activity not found." });
    if (act.submissionScope === "provider") {
      return void res.status(422).json({ error: "Provider-scoped activities do not use training/cohort window rules." });
    }
    if (trainingDurationId) {
      const durationExists = await prisma.trainingDuration.findUnique({ where: { id: trainingDurationId }, select: { id: true } });
      if (!durationExists) return void res.status(400).json({ error: "Invalid trainingDurationId." });
    }
    let row: { id: bigint };
    if (parsed.data.ruleId && /^\d+$/.test(parsed.data.ruleId)) {
      const ruleId = BigInt(parsed.data.ruleId);
      const existing = await (prisma.projectActivityRule as any).findFirst({
        where: { id: ruleId, projectId, projectActivityId: activityId },
        select: { id: true },
      });
      if (!existing) return void res.status(404).json({ error: "Rule not found." });
      const duplicate = await (prisma.projectActivityRule as any).findFirst({
        where: {
          projectId,
          projectActivityId: activityId,
          trainingDurationId,
          id: { not: ruleId },
        },
        select: { id: true },
      });
      if (duplicate) return void res.status(409).json({ error: "A rule for this duration already exists on this activity." });
      row = await (prisma.projectActivityRule as any).update({
        where: { id: ruleId },
        data: {
          ...(parsed.data.anchorType ? { anchorType: parsed.data.anchorType } : {}),
          trainingDurationId,
          openOffsetDays: parsed.data.openOffsetDays ?? null,
          endOffsetDays: parsed.data.endOffsetDays ?? null,
          graceDaysAfterEnd: parsed.data.graceDaysAfterEnd ?? 0,
        },
        select: { id: true },
      });
    } else {
      const duplicate = await (prisma.projectActivityRule as any).findFirst({
        where: {
          projectId,
          projectActivityId: activityId,
          trainingDurationId,
        },
        select: { id: true },
      });
      if (duplicate) return void res.status(409).json({ error: "A rule for this duration already exists on this activity." });
      row = await (prisma.projectActivityRule as any).create({
        data: {
          projectId,
          projectActivityId: activityId,
          trainingDurationId,
          anchorType: parsed.data.anchorType ?? "cohort_anchor",
          openOffsetDays: parsed.data.openOffsetDays ?? null,
          endOffsetDays: parsed.data.endOffsetDays ?? null,
          graceDaysAfterEnd: parsed.data.graceDaysAfterEnd ?? 0,
        },
        select: { id: true },
      });
    }
    res.json({ item: { id: asId(row.id) } });
  },
);

router.delete(
  "/projects/:projectId/activity-windows/:projectActivityId/:ruleId?",
  requirePermission("manage:activity-windows", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const projectActivityId = BigInt(req.params.projectActivityId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const ruleId = req.params.ruleId && /^\d+$/.test(req.params.ruleId) ? BigInt(req.params.ruleId) : null;
    const r = await (prisma.projectActivityRule as any).deleteMany({
      where: { projectId, projectActivityId, ...(ruleId ? { id: ruleId } : {}) },
    });
    if (!r.count) return void res.status(404).json({ error: "Not found." });
    res.json({ ok: true });
  },
);

// ---------- TP activity submissions ----------
router.get(
  "/projects/:projectId/tp-activity-submissions",
  requirePermission("view:activities", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    try { assertTpAssigned(scope); } catch (e) { return void res.status((e as any).status ?? 403).json({ error: (e as Error).message }); }
    const trainingId =
      req.query.trainingId && /^\d+$/.test(String(req.query.trainingId))
        ? BigInt(String(req.query.trainingId))
        : null;
    const providerFilter = scope.providerId ? { trainingProviderId: scope.providerId } : {};
    const items = await prisma.tpActivitySubmission.findMany({
      where: { projectId, ...providerFilter, ...(trainingId ? { trainingId } : {}) },
      orderBy: { id: "desc" },
      take: 200,
      include: {
        activity: true,
        files: true,
        training: { select: { id: true, title: true } },
        cohort: { select: { id: true, code: true, name: true } },
        trainingProvider: { select: { id: true, tpCode: true, name: true } },
      },
    });
    res.json({
      items: items.map((s) => ({
        id: asId(s.id),
        activityCode: s.activity.code,
        activityName: s.activity.name,
        trainingProviderId: asId(s.trainingProviderId),
        tpCode: s.trainingProvider.tpCode,
        tpName: s.trainingProvider.name,
        status: s.status,
        submittedAt: s.submittedAt?.toISOString() ?? null,
        reviewedAt: s.reviewedAt?.toISOString() ?? null,
        reviewComment: s.reviewComment,
        projectActivityId: asId(s.projectActivityId),
        trainingId: s.trainingId ? asId(s.trainingId) : null,
        trainingTitle: s.training?.title ?? null,
        cohortId: s.cohortId ? asId(s.cohortId) : null,
        cohortLabel: s.cohort ? `${s.cohort.code} — ${s.cohort.name}` : null,
        meta: s.meta,
        files: s.files.map((f) => ({ id: asId(f.id), fileName: f.fileName, storagePath: f.storagePath })),
      })),
    });
  },
);

router.post(
  "/projects/:projectId/tp-activity-submissions",
  requirePermission("submit:activity", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const parsed = z
      .object({
        projectActivityId: z.string(),
        trainingProviderId: z.string().optional(),
        trainingId: z.string().optional(),
        cohortId: z.string().optional(),
        status: z.enum(["submitted", "approved", "rejected"]).optional(),
        files: z
          .array(z.object({ fileName: z.string(), storagePath: z.string(), mimeType: z.string().optional(), sizeBytes: z.number().optional() }))
          .optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    let trainingProviderId = parsed.data.trainingProviderId ? BigInt(parsed.data.trainingProviderId) : null;
    if (scope.role === "tp") {
      if (!scope.providerId) return void res.status(403).json({ error: "No TP assignment." });
      trainingProviderId = scope.providerId;
    }
    if (!trainingProviderId) return void res.status(400).json({ error: "trainingProviderId required." });
    const trainingId = parsed.data.trainingId ? BigInt(parsed.data.trainingId) : null;
    const cohortId = parsed.data.cohortId && /^\d+$/.test(parsed.data.cohortId) ? BigInt(parsed.data.cohortId) : null;
    const activity = await (prisma.projectActivity as any).findFirst({
      where: { id: BigInt(parsed.data.projectActivityId), projectId },
      select: { id: true, submissionScope: true },
    });
    if (!activity) return void res.status(404).json({ error: "Activity not found." });
    const assigned = await (prisma.projectActivityAssignment as any).findFirst({
      where: { projectId, projectActivityId: activity.id, trainingProviderId },
      select: { id: true },
    });
    if (!assigned) return void res.status(403).json({ error: "This activity is not assigned to selected provider." });
    let effectiveTrainingId: bigint | null = null;
    let effectiveCohortId: bigint | null = null;
    if (activity.submissionScope === "delivery") {
      if (!trainingId) return void res.status(400).json({ error: "trainingId is required for delivery-scoped activities." });
      const training = await prisma.training.findFirst({
        where: { id: trainingId, projectId, trainingProviderId },
        select: { id: true, trainingProviderId: true },
      });
      if (!training) return void res.status(404).json({ error: "Training not found for provider/project." });
      effectiveTrainingId = training.id;
      try {
        effectiveCohortId = await resolveCohortIdForTrainingDelivery({
          prisma,
          projectId,
          trainingProviderId,
          trainingId: training.id,
          cohortId,
        });
      } catch (e: any) {
        return void res.status(e?.status ?? 400).json({ error: e?.message ?? "Invalid cohort." });
      }
      const gate = await enforceActivitySubmissionWindow({
        projectId,
        activityId: activity.id,
        submissionScope: "delivery",
        trainingId: training.id,
        cohortId: effectiveCohortId,
        now: new Date(),
      });
      if (!gate.ok) return void res.status(gate.status).json({ error: gate.message });
    }
    const sub = await prisma.tpActivitySubmission.create({
      data: {
        projectId,
        trainingProviderId,
        trainingId: effectiveTrainingId,
        cohortId: effectiveCohortId,
        projectActivityId: activity.id,
        status: parsed.data.status ?? "submitted",
        submittedAt: new Date(),
        submittedByUserId: req.auth!.userId,
        files: {
          create: (parsed.data.files ?? []).map((f) => ({
            fileName: f.fileName,
            storagePath: f.storagePath,
            mimeType: f.mimeType ?? null,
            sizeBytes: f.sizeBytes ?? null,
          })),
        },
      },
    });
    res.status(201).json({ item: { id: asId(sub.id) } });
  },
);

router.put(
  "/projects/:projectId/tp-activity-submissions/:submissionId",
  requirePermission("review:activity", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const submissionId = BigInt(req.params.submissionId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = z
      .object({
        status: z.enum(["approved", "rejected"]),
        reviewComment: z.string().min(1),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const existing = await prisma.tpActivitySubmission.findFirst({
      where: { id: submissionId, projectId },
    });
    if (!existing) return void res.status(404).json({ error: "Not found." });
    await prisma.tpActivitySubmission.update({
      where: { id: submissionId },
      data: {
        status: parsed.data.status,
        reviewComment: parsed.data.reviewComment.trim(),
        reviewedAt: new Date(),
        reviewedByUserId: req.auth!.userId,
      },
    });
    await writeSubmissionEvent({
      projectId,
      trainingProviderId: existing.trainingProviderId,
      trainingId: existing.trainingId,
      cohortId: existing.cohortId,
      module: "activities",
      action: "submission_reviewed",
      sourceType: "tp_activity_submission",
      sourceRef: submissionId.toString(),
      payloadRaw: JSON.stringify({
        status: parsed.data.status,
        reviewComment: parsed.data.reviewComment.trim(),
      }),
      actorUserId: req.auth!.userId,
    });
    res.json({ ok: true });
  },
);

router.post(
  "/projects/:projectId/tp-activity-submissions/upload",
  requirePermission("submit:activity", { projectIdParam: "projectId" }),
  activityEvidenceMulter.array("files", 25),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const files = req.files as Express.Multer.File[] | undefined;
    const projectActivityId = String(req.body?.projectActivityId ?? "").trim();
    const notes = String(req.body?.notes ?? "").trim();
    const trainingIdRaw = String(req.body?.trainingId ?? "").trim();
    const cohortIdRaw = String(req.body?.cohortId ?? "").trim();
    if (!files?.length || !projectActivityId) {
      return void res.status(400).json({ error: "Multipart field `files` (1–25 files) and form field `projectActivityId` are required." });
    }
    let trainingProviderId = req.body?.trainingProviderId ? BigInt(String(req.body.trainingProviderId)) : null;
    if (scope.role === "tp") {
      if (!scope.providerId) return void res.status(403).json({ error: "No TP assignment." });
      trainingProviderId = scope.providerId;
    }
    if (!trainingProviderId) return void res.status(400).json({ error: "trainingProviderId required for this user." });
    const training = await prisma.training.findFirst({
      where: { id: /^\d+$/.test(trainingIdRaw) ? BigInt(trainingIdRaw) : -1n, projectId, trainingProviderId },
      select: { id: true },
    });
    const activity = await (prisma.projectActivity as any).findFirst({
      where: { id: BigInt(projectActivityId), projectId },
      select: { id: true, submissionScope: true },
    });
    if (!activity) return void res.status(404).json({ error: "Activity not found." });
    const assigned = await (prisma.projectActivityAssignment as any).findFirst({
      where: { projectId, projectActivityId: activity.id, trainingProviderId },
      select: { id: true },
    });
    if (!assigned) return void res.status(403).json({ error: "This activity is not assigned to selected provider." });
    let effectiveTrainingId: bigint | null = null;
    let effectiveCohortId: bigint | null = null;
    if (activity.submissionScope === "delivery") {
      if (!/^\d+$/.test(trainingIdRaw)) {
        return void res.status(400).json({ error: "Form field trainingId is required for delivery-scoped activity evidence." });
      }
      if (!training) return void res.status(404).json({ error: "Training not found for provider/project." });
      effectiveTrainingId = training.id;
      try {
        effectiveCohortId = await resolveCohortIdForTrainingDelivery({
          prisma,
          projectId,
          trainingProviderId,
          trainingId: training.id,
          cohortId: /^\d+$/.test(cohortIdRaw) ? BigInt(cohortIdRaw) : null,
        });
      } catch (e: any) {
        return void res.status(e?.status ?? 400).json({ error: e?.message ?? "Invalid cohort." });
      }
      const gate = await enforceActivitySubmissionWindow({
        projectId,
        activityId: activity.id,
        submissionScope: "delivery",
        trainingId: training.id,
        cohortId: effectiveCohortId,
        now: new Date(),
      });
      if (!gate.ok) return void res.status(gate.status).json({ error: gate.message });
    }
    const now = new Date();
    const gate =
      activity.submissionScope === "delivery"
        ? await enforceActivitySubmissionWindow({
            projectId,
            activityId: activity.id,
            submissionScope: "delivery",
            trainingId: effectiveTrainingId,
            cohortId: effectiveCohortId,
            now,
          })
        : {
            ok: true as const,
            startDate: null,
            endDate: null,
            endDateEffective: null,
            graceDaysAfterEnd: 0,
          };
    if (!gate.ok) return void res.status(gate.status).json({ error: gate.message });
    const isLate = gate.endDate ? dateOnlyUtc(now) > dateOnlyUtc(gate.endDate) : false;
    const fileCreates = files.map((file) => ({
      fileName: file.originalname,
      storagePath: path.posix.join("activity-evidence", String(projectId), file.filename),
      mimeType: file.mimetype || null,
      sizeBytes: file.size ?? null,
    }));
    const sub = await prisma.tpActivitySubmission.create({
      data: {
        projectId,
        trainingProviderId,
        trainingId: effectiveTrainingId,
        cohortId: effectiveCohortId,
        projectActivityId: activity.id,
        status: "submitted",
        submittedAt: now,
        submittedByUserId: req.auth!.userId,
        meta: ({
          ...(notes ? { notes } : {}),
          windowEndDate: gate.endDate ? gate.endDate.toISOString().slice(0, 10) : null,
          windowEndDateEffective: gate.endDateEffective ? gate.endDateEffective.toISOString().slice(0, 10) : null,
          windowGraceDaysAfterEnd: gate.graceDaysAfterEnd,
          submittedLate: isLate,
        } as Prisma.InputJsonValue),
        files: { create: fileCreates },
      },
    });
    res.status(201).json({ item: { id: asId(sub.id) }, fileCount: files.length });
  },
);

router.get(
  "/projects/:projectId/activity-files/:fileId/download",
  requirePermission("view:activities", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const fileId = BigInt(req.params.fileId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const row = await prisma.tpActivitySubmissionFile.findFirst({
      where: { id: fileId, submission: { projectId } },
      include: { submission: true },
    });
    if (!row) return void res.status(404).json({ error: "Not found." });
    if (scope.providerId && row.submission.trainingProviderId !== scope.providerId) {
      return void res.status(403).json({ error: "No access to this file." });
    }
    const abs = path.resolve(env.uploadRoot, row.storagePath);
    const rootResolved = path.resolve(env.uploadRoot);
    const rel = path.relative(rootResolved, abs);
    if (rel.startsWith("..") || path.isAbsolute(rel)) {
      return void res.status(403).json({ error: "Invalid path." });
    }
    if (!fs.existsSync(abs)) return void res.status(404).json({ error: "File missing on disk." });
    res.download(abs, row.fileName);
  },
);

// ---------- Outcome resubmission requests ----------
router.get(
  "/projects/:projectId/outcome-resubmission-requests",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const rows = await prisma.submissionEvent.findMany({
      where: {
        projectId,
        module: "outcomes",
        action: "resubmission_requested",
        ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}),
      },
      orderBy: { id: "desc" },
      take: 300,
    });
    const requestIds = rows.map((r) => r.id.toString());
    const decisions = requestIds.length
      ? await prisma.submissionEvent.findMany({
          where: {
            projectId,
            module: "outcomes",
            action: { in: ["resubmission_approved", "resubmission_rejected", "resubmission_consumed"] },
            sourceRef: { in: requestIds },
          },
          orderBy: { id: "desc" },
        })
      : [];
    const decisionByRequest = new Map<string, (typeof decisions)[number]>();
    for (const d of decisions) {
      if (!d.sourceRef) continue;
      if (!decisionByRequest.has(d.sourceRef)) decisionByRequest.set(d.sourceRef, d);
    }
    const items = rows.map((r) => {
      const d = decisionByRequest.get(r.id.toString());
      const meta = (r.meta ?? {}) as Record<string, unknown>;
      const dMeta = (d?.meta ?? {}) as Record<string, unknown>;
      let status: "requested" | "approved" | "rejected" | "consumed" = "requested";
      if (d?.action === "resubmission_approved") status = "approved";
      if (d?.action === "resubmission_rejected") status = "rejected";
      if (d?.action === "resubmission_consumed") status = "consumed";
      return {
        id: asId(r.id),
        trainingProviderId: r.trainingProviderId ? asId(r.trainingProviderId) : null,
        trainingId: r.trainingId ? asId(r.trainingId) : null,
        cohortId: r.cohortId ? asId(r.cohortId) : null,
        reportType: String(meta.reportType ?? ""),
        reason: typeof meta.reason === "string" ? meta.reason : null,
        status,
        requestedAt: r.createdAt.toISOString(),
        reviewedAt: d?.createdAt?.toISOString() ?? null,
        reviewerComment: typeof dMeta.comment === "string" ? dMeta.comment : null,
      };
    });
    res.json({ items });
  },
);

router.post(
  "/projects/:projectId/outcome-resubmission-requests",
  requirePermission("submit:outcomes", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const parsed = z
      .object({
        trainingProviderId: z.string().optional(),
        trainingId: z.string(),
        cohortId: z.string().optional(),
        stageKey: z.string().min(1).max(40).optional(),
        reportType: z.string().min(1),
        reason: z.string().min(5).max(2000),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    let trainingProviderId = parsed.data.trainingProviderId ? BigInt(parsed.data.trainingProviderId) : null;
    if (scope.role === "tp") {
      if (!scope.providerId) return void res.status(403).json({ error: "No TP assignment." });
      trainingProviderId = scope.providerId;
    }
    if (!trainingProviderId) return void res.status(400).json({ error: "trainingProviderId required." });
    const trainingId = BigInt(parsed.data.trainingId);
    const training = await prisma.training.findFirst({
      where: { id: trainingId, projectId, trainingProviderId },
      select: { id: true },
    });
    if (!training) return void res.status(404).json({ error: "Training not found for provider/project." });
    let effectiveCohortId: bigint | null = null;
    try {
      effectiveCohortId = await resolveCohortIdForTrainingDelivery({
        prisma,
        projectId,
        trainingProviderId,
        trainingId: training.id,
        cohortId: parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null,
      });
    } catch (e: any) {
      return void res.status(e?.status ?? 400).json({ error: e?.message ?? "Invalid cohort." });
    }
    const outcomeStageKey = parsed.data.stageKey?.trim() || null;
    if (parsed.data.reportType === "completion") {
      const hasDropout = await ensureDropoutSubmittedBeforeCompletion({
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        stageKey: outcomeStageKey,
      });
      if (!hasDropout) {
        return void res.status(422).json({
          error: "Completion resubmission request blocked: submit and process dropout report first for this scope.",
        });
      }
    }
    if (parsed.data.reportType === "completion" || parsed.data.reportType === "dropout") {
      const coverage = await getAttendanceCoverageForOutcomeScope({
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
      });
      if (coverage.expectedSlots > 0 && coverage.submittedRows < coverage.expectedSlots) {
        return void res.status(422).json({
          error: `${parsed.data.reportType === "dropout" ? "Dropout" : "Completion"} report blocked: attendance is incomplete for this scope.`,
          details: {
            expectedAttendanceRows: coverage.expectedSlots,
            submittedAttendanceRows: coverage.submittedRows,
          },
        });
      }
    }
    const existingBatch = await prisma.outcomeReportBatch.findFirst({
      where: {
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        reportType: parsed.data.reportType,
        status: "processed",
        ...(outcomeStageKey ? { meta: { path: "$.stageKey", equals: outcomeStageKey } as Prisma.JsonFilter } : {}),
      },
      select: { id: true },
    });
    if (!existingBatch) {
      return void res.status(422).json({ error: "No processed report exists for this scope, so resubmission request is not needed." });
    }
    const scopeRef = outcomeResubScopeRef(trainingProviderId, trainingId, effectiveCohortId, parsed.data.reportType, outcomeStageKey);
    const latestRequest = await prisma.submissionEvent.findFirst({
      where: { projectId, module: "outcomes", action: "resubmission_requested", sourceRef: scopeRef },
      orderBy: { id: "desc" },
      select: { id: true },
    });
    if (latestRequest) {
      const latestDecision = await prisma.submissionEvent.findFirst({
        where: {
          projectId,
          module: "outcomes",
          action: { in: ["resubmission_approved", "resubmission_rejected", "resubmission_consumed"] },
          sourceRef: latestRequest.id.toString(),
        },
        orderBy: { id: "desc" },
        select: { id: true, action: true },
      });
      if (!latestDecision || latestDecision.action === "resubmission_approved") {
        return void res.status(409).json({ error: "A resubmission request is already pending or approved for this scope." });
      }
    }
    const row = await prisma.submissionEvent.create({
      data: {
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        module: "outcomes",
        action: "resubmission_requested",
        sourceType: "workflow",
        sourceRef: scopeRef,
        actorUserId: req.auth!.userId,
        meta: {
          reportType: parsed.data.reportType,
          reason: parsed.data.reason.trim(),
          ...(outcomeStageKey ? { stageKey: outcomeStageKey } : {}),
        } as Prisma.InputJsonValue,
      },
      select: { id: true },
    });
    res.status(201).json({ item: { id: asId(row.id) } });
  },
);

router.post(
  "/projects/:projectId/outcome-resubmission-requests/:requestId/decision",
  requirePermission("manage:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const requestId = BigInt(req.params.requestId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const parsed = z
      .object({ decision: z.enum(["approved", "rejected"]), comment: z.string().min(5).max(2000) })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    const request = await prisma.submissionEvent.findFirst({
      where: { id: requestId, projectId, module: "outcomes", action: "resubmission_requested" },
      select: { id: true, actorUserId: true },
    });
    if (!request) return void res.status(404).json({ error: "Resubmission request not found." });
    if (request.actorUserId && request.actorUserId === req.auth!.userId) {
      return void res.status(422).json({ error: "Requester cannot approve/reject their own resubmission request." });
    }
    const existingDecision = await prisma.submissionEvent.findFirst({
      where: {
        projectId,
        module: "outcomes",
        action: { in: ["resubmission_approved", "resubmission_rejected", "resubmission_consumed"] },
        sourceRef: requestId.toString(),
      },
      orderBy: { id: "desc" },
      select: { id: true },
    });
    if (existingDecision) return void res.status(409).json({ error: "This request already has a decision." });
    await prisma.submissionEvent.create({
      data: {
        projectId,
        module: "outcomes",
        action: parsed.data.decision === "approved" ? "resubmission_approved" : "resubmission_rejected",
        sourceType: "workflow",
        sourceRef: requestId.toString(),
        actorUserId: req.auth!.userId,
        meta: { comment: parsed.data.comment.trim() } as Prisma.InputJsonValue,
      },
    });
    await writeSubmissionEvent({
      projectId,
      module: "outcomes",
      action: parsed.data.decision === "approved" ? "resubmission_decision_approved" : "resubmission_decision_rejected",
      sourceType: "workflow",
      sourceRef: requestId.toString(),
      payloadRaw: JSON.stringify({ comment: parsed.data.comment.trim() }),
      actorUserId: req.auth!.userId,
    });
    res.json({ ok: true });
  },
);

// ---------- Outcome CSV templates (catalog + empty/example CSV) ----------
router.get(
  "/projects/:projectId/outcome-templates",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const items = await getOutcomeTemplatesForProject(prisma, projectId);
    res.json({ items });
  },
);

router.get(
  "/projects/:projectId/outcome-templates/:reportType/csv",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const reportType = String(req.params.reportType ?? "").trim();
    const scope = await resolveScope(projectId, req.auth!.userId);
    let providerId: bigint | null = scope.providerId ?? null;
    if (!providerId && req.query.trainingProviderId) {
      const raw = String(req.query.trainingProviderId).trim();
      if (/^\d+$/.test(raw)) providerId = BigInt(raw);
    }
    let trainingId: bigint | null = null;
    if (req.query.trainingId) {
      const raw = String(req.query.trainingId).trim();
      if (/^\d+$/.test(raw)) trainingId = BigInt(raw);
    }
    let cohortId: bigint | null = null;
    if (req.query.cohortId) {
      const raw = String(req.query.cohortId).trim();
      if (/^\d+$/.test(raw)) cohortId = BigInt(raw);
    }
    // Templates are stage-free. Downstream eligibility checks will use final-stage where applicable.
    const stageKey = null;

    let prefilledRows: Array<Record<string, string>> | undefined;
    if (providerId) {
      const prerequisiteByReport: Record<string, string | null> = {
        completion: null,
        certification: "completion",
        employment_placement: "certification",
        locality_compliant: "employment_placement",
        job_retention_3m: "employment_placement",
        dropout: null,
      };
      const excludeIfHasPositive: Record<string, string[]> = {
        completion: ["dropout"],
        certification: ["dropout"],
        employment_placement: ["dropout"],
        locality_compliant: ["dropout"],
        job_retention_3m: ["dropout"],
        dropout: ["completion", "certification", "employment_placement", "locality_compliant", "job_retention_3m"],
      };
      const trainees = await prisma.trainee.findMany({
        where: {
          projectId,
          trainingProviderId: providerId,
          rosterRole: TRACKED_ROSTER_WHERE,
          ...(trainingId ? { trainingId } : {}),
          ...(cohortId ? { cohortId } : {}),
        },
        select: {
          traineeUniqueId: true,
          externalBeneficiaryId: true,
          firstName: true,
          fatherName: true,
          grandfatherName: true,
        },
        orderBy: { traineeUniqueId: "asc" },
        take: 5000,
      });
      const traineeIds = await prisma.trainee.findMany({
        where: {
          projectId,
          trainingProviderId: providerId,
          rosterRole: TRACKED_ROSTER_WHERE,
          ...(trainingId ? { trainingId } : {}),
          ...(cohortId ? { cohortId } : {}),
        },
        select: { id: true, traineeUniqueId: true },
        orderBy: { traineeUniqueId: "asc" },
        take: 5000,
      });
      const byUniqueId = new Map(traineeIds.map((t) => [t.traineeUniqueId, t.id]));
      const outcomeTypeByReport: Record<string, string> = {
        completion: "completion",
        certification: "certification",
        dropout: "dropout",
        employment_placement: "employment_placement",
        locality_compliant: "locality_compliant",
        job_retention_3m: "job_retention_3m",
      };
      const hasOutcomeType = OUTCOME_TEMPLATE_DEFS.find((d) => d.reportType === reportType)?.columns.some((c) => c.key === "outcome_type");
      const fixedOutcomeType = outcomeTypeByReport[reportType];
      const buildTraineeName = (t: { firstName: string; fatherName: string | null; grandfatherName: string | null }) =>
        [t.firstName, t.fatherName ?? "", t.grandfatherName ?? ""].join(" ").replace(/\s+/g, " ").trim();
      const INDICATOR_CODE_BY_OUTCOME_TYPE: Record<string, string> = {
        completion: "training_completion_rate",
        certification: "training_certification_rate",
        employment_placement: "employment_placement_rate",
        locality_compliant: "locality_compliant_placement_rate",
        job_retention_3m: "job_retention_3_month_rate",
        dropout: "trainee_dropout_rate",
      };
      const requiredPriorOutcomeType = prerequisiteByReport[reportType] ?? null;
      const outcomeTypesToCheck = [...new Set([fixedOutcomeType, requiredPriorOutcomeType].filter(Boolean))] as string[];
      const indicatorCodesToCheck = outcomeTypesToCheck
        .map((ot) => INDICATOR_CODE_BY_OUTCOME_TYPE[ot] ?? null)
        .filter(Boolean) as string[];
      const indicators = await prisma.projectIndicator.findMany({
        where: { projectId, code: { in: indicatorCodesToCheck } },
        select: {
          code: true,
          stages: { select: { stageKey: true, isFinalStage: true, sortOrder: true } },
        },
      });
      const finalStageKeyByIndicatorCode = new Map<string, string | null>();
      for (const ind of indicators) {
        const stages = [...(ind.stages ?? [])].sort((a, b) => a.sortOrder - b.sortOrder);
        const finalStage = stages.find((s) => s.isFinalStage) ?? stages[stages.length - 1];
        finalStageKeyByIndicatorCode.set(ind.code, finalStage ? finalStage.stageKey : null);
      }
      const finalStageKeyByOutcomeType = new Map<string, string | null>();
      for (const ot of outcomeTypesToCheck) {
        const ic = INDICATOR_CODE_BY_OUTCOME_TYPE[ot];
        finalStageKeyByOutcomeType.set(ot, finalStageKeyByIndicatorCode.get(ic) ?? null);
      }
      const stageAwareOutcomeTypes = new Set<string>();
      for (const [ot, sk] of finalStageKeyByOutcomeType.entries()) {
        if (sk) stageAwareOutcomeTypes.add(ot);
      }

      const existingPositives = await prisma.traineeOutcome.findMany({
        where: {
          projectId,
          trainingProviderId: providerId,
          ...(trainingId ? { trainingId } : {}),
          ...(cohortId ? { cohortId } : {}),
          reportedValue: true,
        },
        select: { traineeId: true, outcomeType: true, meta: true },
      });
      const positivesByTrainee = new Map<string, Set<string>>();
      for (const row of existingPositives) {
        const key = row.traineeId.toString();
        if (!positivesByTrainee.has(key)) positivesByTrainee.set(key, new Set());
        const meta = row.meta && typeof row.meta === "object" && !Array.isArray(row.meta) ? (row.meta as Record<string, unknown>) : {};
        const sk = typeof meta.stageKey === "string" ? meta.stageKey : null;
        const ok = stageAwareOutcomeTypes.has(row.outcomeType) ? `${row.outcomeType}:${sk ?? "none"}` : row.outcomeType;
        positivesByTrainee.get(key)!.add(ok);
      }
      const requiredPrior = prerequisiteByReport[reportType] ?? null;
      const exclusions = excludeIfHasPositive[reportType] ?? [];
      const requiredPriorKey =
        requiredPrior && stageAwareOutcomeTypes.has(requiredPrior)
          ? `${requiredPrior}:${finalStageKeyByOutcomeType.get(requiredPrior) ?? "none"}`
          : requiredPrior;
      // For dropout templates include ALL trainees so the TP can mark each one Y/N.
      // Other report types still exclude trainees who already have a positive
      // outcome in a prerequisite or excluded type.
      const skipExclusions = reportType === "dropout";
      prefilledRows = trainees.map((t) => ({
        external_beneficiary_id: t.externalBeneficiaryId ?? "",
        trainee_unique_id: t.traineeUniqueId,
        trainee_name: buildTraineeName(t),
        ...(hasOutcomeType && fixedOutcomeType ? { outcome_type: fixedOutcomeType } : {}),
      })).filter((row) => {
        const tid = byUniqueId.get(row.trainee_unique_id)?.toString();
        if (!tid) return false;
        if (skipExclusions) return true;
        const positives = positivesByTrainee.get(tid) ?? new Set<string>();
        if (requiredPriorKey && !positives.has(requiredPriorKey)) return false;
        if (exclusions.some((x) => traineePositiveSetHas(positives, x))) return false;
        return true;
      });
      if (reportType === "dropout" && trainingId) {
        const projections = await computeDropoutProjections({
          projectId,
          trainingProviderId: providerId,
          trainingId,
          cohortId,
        });
        const projectionByUid = new Map(projections.map((p) => [p.traineeUniqueId, p]));
        // systemDropoutFinal (attendance < 80% after training ended) → pre-fill Y; this is
        // FINAL — the upload is rejected if such a row is missing or flipped to N (attendance is
        // the TP's own data, so corrections belong in attendance, not in this report).
        // tpReportedDropout (TP already confirmed) → Y with TP reason.
        // systemDropoutRisk (at-risk, not yet final) → N with warning note.
        // TP can override any row; system-final rows must be present as Y.
        prefilledRows = prefilledRows
          .map((row) => {
            const p = projectionByUid.get(row.trainee_unique_id);
            if (p?.systemDropoutFinal) {
              return {
                ...row,
                reported_value: "Y",
                dropout_reason: "low_attendance_auto",
                dropout_notes: "",
              };
            }
            if (p?.tpReportedDropout) {
              return {
                ...row,
                reported_value: "Y",
                dropout_reason: p.reasonCode ?? "other",
                dropout_notes: "",
              };
            }
            return {
              ...row,
              reported_value: "N",
              dropout_reason: "",
              dropout_notes: "",
            };
          })
          // Sort Y (dropout) rows to the top for easy review.
          .sort((a: Record<string, string>, b: Record<string, string>) => {
            if (a.reported_value === "Y" && b.reported_value !== "Y") return -1;
            if (a.reported_value !== "Y" && b.reported_value === "Y") return 1;
            return (a.trainee_unique_id ?? "").localeCompare(b.trainee_unique_id ?? "");
          });
      }
    }

    const body = buildOutcomeTemplateCsvBody(reportType, prefilledRows);
    if (!body) return void res.status(404).json({ error: "Unknown template." });
    const safeName = reportType.replace(/[^\w.-]+/g, "_");
    res.setHeader("Content-Type", "text/csv; charset=utf-8");
    res.setHeader("Content-Disposition", `attachment; filename="${safeName}_template.csv"`);
    res.send(body);
  },
);

// ---------- Outcomes ----------
router.get(
  "/projects/:projectId/outcome-batches",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const trainingId =
      req.query.trainingId && /^\d+$/.test(String(req.query.trainingId))
        ? BigInt(String(req.query.trainingId))
        : null;
    const cohortId =
      req.query.cohortId && /^\d+$/.test(String(req.query.cohortId))
        ? BigInt(String(req.query.cohortId))
        : null;
    const stageKey =
      typeof req.query.stageKey === "string" && req.query.stageKey.trim().length > 0
        ? req.query.stageKey.trim()
        : null;
    const providerFilter = scope.providerId ? { trainingProviderId: scope.providerId } : {};
    const items = await prisma.outcomeReportBatch.findMany({
      where: {
        projectId,
        ...providerFilter,
        ...(trainingId ? { trainingId } : {}),
        ...(cohortId ? { cohortId } : {}),
        ...(stageKey ? { meta: { path: "$.stageKey", equals: stageKey } as Prisma.JsonFilter } : {}),
      },
      orderBy: { id: "desc" },
      take: 100,
    });
    res.json({
      items: items.map((b) => ({
        id: asId(b.id),
        reportType: b.reportType,
        sourceFilename: b.sourceFilename,
        status: b.status,
        totalRows: b.totalRows,
        validRows: b.validRows,
        invalidRows: b.invalidRows,
        trainingProviderId: asId(b.trainingProviderId),
        trainingId: b.trainingId ? asId(b.trainingId) : null,
        cohortId: b.cohortId ? asId(b.cohortId) : null,
        stageKey: (() => {
          const m = (b.meta ?? {}) as Record<string, unknown>;
          return typeof m.stageKey === "string" ? m.stageKey : null;
        })(),
        createdAt: b.createdAt.toISOString(),
      })),
    });
  },
);

// --- Admin: delete processed outcome report batches (with full verification cleanup) ---
//
// TERMINOLOGY: an `OutcomeReportBatch.id` is a REPORT batch (one uploaded dropout/completion/...
// report). A `TrainingBatch` is a CLASS section (delivery batch) — report batches merely carry a
// reference to one in their `batchId` column. Everything below keys off REPORT batch ids.

type OutcomeReportBatchTarget = {
  id: bigint;
  reportType: string;
  trainingProviderId: bigint;
  trainingId: bigint | null;
  cohortId: bigint | null;
};

type OutcomeBatchDeletionCounters = {
  deletedBatches: number;
  deletedOutcomes: number;
  resetVncompSubjects: number;
  removedDropoutRecords: number;
  claimsReset: number;
  claimsRestored: number;
};

type DeletableReportBatchRows = Array<{
  traineeId: bigint;
  outcomeType: string;
  reportBatchId: bigint | null;
}>;

type LoadDeletableResult =
  | { ok: true; batches: OutcomeReportBatchTarget[]; affectedRows: DeletableReportBatchRows }
  | { ok: false; status: number; error: string; details?: unknown };

/**
 * Pre-flight for deletion, shared by the single and bulk routes so both enforce identical rules:
 * the report batch must exist, must be `processed`, and every outcome row it owns must have an
 * outcome_type equal to that batch's reportType (verification cleanup keys off reportType, so a
 * mixed-type batch must never be silently wiped).
 */
async function loadDeletableOutcomeReportBatches(args: {
  projectId: bigint;
  batchIds: bigint[];
}): Promise<LoadDeletableResult> {
  if (args.batchIds.length === 0) {
    return { ok: false, status: 404, error: "Outcome batch not found." };
  }
  const batches = await prisma.outcomeReportBatch.findMany({
    where: { id: { in: args.batchIds }, projectId: args.projectId },
    select: { id: true, status: true, reportType: true, trainingProviderId: true, trainingId: true, cohortId: true },
    orderBy: { id: "asc" },
  });
  const foundIds = new Set(batches.map((b) => b.id.toString()));
  const missingIds = args.batchIds.filter((id) => !foundIds.has(id.toString()));
  if (missingIds.length > 0) {
    return {
      ok: false,
      status: 404,
      error: "Outcome batch not found.",
      details: { missingBatchIds: missingIds.map((id) => id.toString()) },
    };
  }

  const notProcessed = batches.filter((b) => b.status !== "processed");
  if (notProcessed.length > 0) {
    return {
      ok: false,
      status: 422,
      error:
        notProcessed.length === batches.length
          ? "Only processed batches can be deleted."
          : "Some report batches are not processed yet and cannot be deleted.",
      details: { batchIds: notProcessed.map((b) => b.id.toString()) },
    };
  }

  const providerIds = [...new Set(batches.map((b) => b.trainingProviderId))];
  const affectedRows = (await prisma.traineeOutcome.findMany({
    where: {
      projectId: args.projectId,
      trainingProviderId: { in: providerIds },
      reportBatchId: { in: args.batchIds },
    },
    select: { traineeId: true, outcomeType: true, reportBatchId: true },
  })) as DeletableReportBatchRows;

  // Type guard: every row's outcomeType must match the reportType of the batch that owns it.
  const reportTypeByBatch = new Map(batches.map((b) => [b.id.toString(), b.reportType]));
  const mismatched = new Map<string, Set<string>>();
  for (const row of affectedRows) {
    if (row.reportBatchId == null) continue;
    const owner = row.reportBatchId.toString();
    const expected = reportTypeByBatch.get(owner);
    if (expected && row.outcomeType !== expected) {
      const set = mismatched.get(owner) ?? new Set<string>();
      set.add(row.outcomeType);
      mismatched.set(owner, set);
    }
  }
  if (mismatched.size > 0) {
    const offenders = [...mismatched.entries()].map(([id, types]) => ({
      reportBatchId: id,
      reportType: reportTypeByBatch.get(id) ?? null,
      rowOutcomeTypes: [...types],
    }));
    const first = offenders[0]!;
    return {
      ok: false,
      status: 422,
      error:
        "Batch cannot be deleted: it contains rows whose outcome_type does not match the batch report type. Resolve these rows manually first.",
      details:
        offenders.length === 1
          ? {
              batchReportType: first.reportType,
              rowOutcomeTypes: first.rowOutcomeTypes,
              mismatchedOutcomeTypes: first.rowOutcomeTypes,
            }
          : { batches: offenders },
    };
  }

  return {
    ok: true,
    batches: batches.map((b) => ({
      id: b.id,
      reportType: b.reportType,
      trainingProviderId: b.trainingProviderId,
      trainingId: b.trainingId,
      cohortId: b.cohortId,
    })),
    affectedRows,
  };
}

/**
 * Deletes the given REPORT batches in one transaction: their trainee_outcome rows first, then the
 * verification cleanup (undo AUTO dropout marks, drop dropout cross-records, re-derive
 * tpClaimValue) driven by whatever positives remain, then the report batches themselves.
 *
 * A single batch is just the one-element case, so the single and bulk routes run literally the
 * same code and end in exactly the same state.
 */
async function deleteOutcomeReportBatches(args: {
  projectId: bigint;
  batches: OutcomeReportBatchTarget[];
  affectedRows: DeletableReportBatchRows;
}): Promise<OutcomeBatchDeletionCounters> {
  const counters: OutcomeBatchDeletionCounters = {
    deletedBatches: 0,
    deletedOutcomes: 0,
    resetVncompSubjects: 0,
    removedDropoutRecords: 0,
    claimsReset: 0,
    claimsRestored: 0,
  };
  const batchIds = args.batches.map((b) => b.id);
  const providerIds = [...new Set(args.batches.map((b) => b.trainingProviderId))];
  const affectedBigIntIds = [...new Set(args.affectedRows.map((o) => o.traineeId.toString()))].map((id) => BigInt(id));

  await prisma.$transaction(async (tx) => {
    // 1. Delete trainee_outcomes for these REPORT batches. Scoped by reportBatchId (per-report,
    //    per-type) — NOT the delivery batchId column, which is shared across dropout/completion rows.
    const deleted = await tx.traineeOutcome.deleteMany({
      where: {
        projectId: args.projectId,
        trainingProviderId: { in: providerIds },
        reportBatchId: { in: batchIds },
      },
    });
    counters.deletedOutcomes = deleted.count;

    if (affectedBigIntIds.length > 0) {
      // 2. Which positive outcomes do affected trainees STILL have after the deletion?
      const remainingPositives = await tx.traineeOutcome.findMany({
        where: {
          projectId: args.projectId,
          trainingProviderId: { in: providerIds },
          traineeId: { in: affectedBigIntIds },
          reportedValue: true,
        },
        select: { traineeId: true, outcomeType: true, meta: true },
      });
      const stillDropoutIds = new Set(
        remainingPositives.filter((r) => r.outcomeType === "dropout").map((r) => r.traineeId.toString()),
      );

      // 3. Cleanup open verification runs for these providers. Dropout auto-marks (V-NCOMP +
      //    verification_sample_run_dropouts) are written at draw time and by backfill into runs
      //    of ANY report type (usually completion runs), so we iterate ALL open runs and make
      //    every step idempotent per run instead of filtering by reportType.
      const openRuns = await tx.verificationSampleRun.findMany({
        where: { projectId: args.projectId, trainingProviderId: { in: providerIds }, status: "open" },
        select: { id: true, reportType: true, stageKey: true },
      });

      for (const run of openRuns) {
        const resettableIds = affectedBigIntIds.filter((id) => !stillDropoutIds.has(id.toString()));

        // 3a. Undo AUTO dropout marks only: draw-time rows carry no reviewerNote, backfill rows
        //     carry the "Auto-marked: dropout" note. Human verdicts are never touched.
        if (resettableIds.length > 0) {
          const unmarked = await tx.verificationSampleSubject.updateMany({
            where: {
              runId: run.id,
              traineeId: { in: resettableIds },
              verificationStatusCode: "V-NCOMP",
              verifiedByUserId: null,
              OR: [{ reviewerNote: null }, { reviewerNote: { contains: "Auto-marked: dropout" } }],
            },
            data: {
              verificationStatusCode: null,
              verifiedValue: null,
              verifiedAt: null,
              reviewerNote: null,
            },
          });
          counters.resetVncompSubjects += unmarked.count;

          // 3b. Remove dropout cross-records for trainees that are no longer dropouts.
          const removedDropouts = await tx.verificationSampleRunDropout.deleteMany({
            where: { runId: run.id, traineeId: { in: resettableIds } },
          });
          counters.removedDropoutRecords += removedDropouts.count;
        }

        // 3c. Re-derive tpClaimValue for this run's OWN report type (mirrors
        //     autoBackfillVerificationRuns, including stageKey matching), so a deletion can
        //     never bleed into runs of other report types.
        if (run.reportType === "trainee_registration") continue;
        const claimedNow = new Set<string>();
        for (const row of remainingPositives) {
          if (row.outcomeType !== run.reportType) continue;
          const meta = row.meta && typeof row.meta === "object" && !Array.isArray(row.meta) ? (row.meta as Record<string, unknown>) : {};
          const sk = typeof meta.stageKey === "string" ? meta.stageKey : null;
          if (run.stageKey && sk !== run.stageKey) continue;
          claimedNow.add(row.traineeId.toString());
        }
        const toClaim = affectedBigIntIds.filter((id) => claimedNow.has(id.toString()));
        const toUnclaim = affectedBigIntIds.filter((id) => !claimedNow.has(id.toString()));
        if (toClaim.length > 0) {
          const restored = await tx.verificationSampleSubject.updateMany({
            where: { runId: run.id, traineeId: { in: toClaim }, tpClaimValue: false },
            data: { tpClaimValue: true },
          });
          counters.claimsRestored += restored.count;
        }
        if (toUnclaim.length > 0) {
          const reset = await tx.verificationSampleSubject.updateMany({
            where: { runId: run.id, traineeId: { in: toUnclaim }, tpClaimValue: true },
            data: { tpClaimValue: false },
          });
          counters.claimsReset += reset.count;
        }
      }
    }

    // 4. Delete the OutcomeReportBatch rows themselves
    const gone = await tx.outcomeReportBatch.deleteMany({ where: { id: { in: batchIds } } });
    counters.deletedBatches = gone.count;
  });

  return counters;
}

function deletionErrorResponse(res: Response, result: { status: number; error: string; details?: unknown }) {
  return void res
    .status(result.status)
    .json({ error: result.error, ...(result.details !== undefined ? { details: result.details } : {}) });
}

// --- Admin: delete a single processed outcome report batch (with full verification cleanup) ---
router.delete(
  "/projects/:projectId/outcome-batches/:batchId",
  requirePermission("manage:indicators", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res: Response) => {
    const projectId = BigInt(req.params.projectId);
    const batchId = BigInt(req.params.batchId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });

    const loaded = await loadDeletableOutcomeReportBatches({ projectId, batchIds: [batchId] });
    if (!loaded.ok) return deletionErrorResponse(res, loaded);

    const target = loaded.batches[0]!;
    const counters = await deleteOutcomeReportBatches({
      projectId,
      batches: loaded.batches,
      affectedRows: loaded.affectedRows,
    });

    await writeAuditEvent({
      projectId,
      trainingProviderId: target.trainingProviderId,
      trainingId: target.trainingId,
      cohortId: target.cohortId,
      module: "outcomes",
      action: "batch_deleted",
      sourceType: "outcome_report_batch",
      sourceRef: batchId.toString(),
      payloadRaw: JSON.stringify({
        batchId: batchId.toString(),
        reportType: target.reportType,
        deletedOutcomes: counters.deletedOutcomes,
        resetVncompSubjects: counters.resetVncompSubjects,
        removedDropoutRecords: counters.removedDropoutRecords,
        claimsReset: counters.claimsReset,
        claimsRestored: counters.claimsRestored,
      }),
      meta: {
        batchId: batchId.toString(),
        reportType: target.reportType,
        deletedOutcomes: counters.deletedOutcomes,
        resetVncompSubjects: counters.resetVncompSubjects,
        removedDropoutRecords: counters.removedDropoutRecords,
        claimsReset: counters.claimsReset,
        claimsRestored: counters.claimsRestored,
      } as Prisma.InputJsonValue,
      actorUserId: req.auth!.userId,
    });

    res.json({
      ok: true,
      deletedOutcomes: counters.deletedOutcomes,
      resetVncompSubjects: counters.resetVncompSubjects,
      removedDropoutRecords: counters.removedDropoutRecords,
      claimsReset: counters.claimsReset,
      claimsRestored: counters.claimsRestored,
    });
  },
);

router.post(
  "/projects/:projectId/outcome-batches",
  requirePermission("submit:outcomes", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const parsed = z
      .object({
        trainingProviderId: z.string().optional(),
        trainingId: z.string(),
        cohortId: z.string().optional(),
        stageKey: z.string().min(1).max(40).optional(),
        reportType: z.string().min(1),
        sourceFilename: z.string().optional(),
        outcomes: z
          .array(
            z.object({
              traineeId: z.string(),
              outcomeType: z.string(),
              statusDate: z.string().optional(),
              reportedValue: z.boolean().optional().nullable(),
              meta: z.record(z.unknown()).optional(),
            }),
          )
          .optional(),
      })
      .safeParse(req.body);
    if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    let trainingProviderId = parsed.data.trainingProviderId ? BigInt(parsed.data.trainingProviderId) : null;
    if (scope.role === "tp") {
      if (!scope.providerId) return void res.status(403).json({ error: "No TP assignment." });
      trainingProviderId = scope.providerId;
    }
    const trainingId = BigInt(parsed.data.trainingId);
    if (!trainingProviderId) return void res.status(400).json({ error: "trainingProviderId required." });
    const training = await prisma.training.findFirst({
      where: { id: trainingId, projectId, trainingProviderId },
      select: { id: true },
    });
    if (!training) return void res.status(404).json({ error: "Training not found for provider/project." });
    let effectiveCohortId: bigint | null = null;
    try {
      effectiveCohortId = await resolveCohortIdForTrainingDelivery({
        prisma,
        projectId,
        trainingProviderId,
        trainingId: training.id,
        cohortId: parsed.data.cohortId ? BigInt(parsed.data.cohortId) : null,
      });
    } catch (e: any) {
      return void res.status(e?.status ?? 400).json({ error: e?.message ?? "Invalid cohort." });
    }
    const outcomeStageKey = parsed.data.stageKey?.trim() || null;
    if (parsed.data.reportType === "completion") {
      const hasDropout = await ensureDropoutSubmittedBeforeCompletion({
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        stageKey: outcomeStageKey,
      });
      if (!hasDropout) {
        return void res.status(422).json({
          error: "Completion report blocked: submit and process dropout report first for this scope.",
        });
      }
    }
    const existingBatch = await prisma.outcomeReportBatch.findFirst({
      where: {
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        reportType: parsed.data.reportType,
        status: "processed",
        ...(outcomeStageKey ? { meta: { path: "$.stageKey", equals: outcomeStageKey } as Prisma.JsonFilter } : {}),
      },
      select: { id: true },
    });
    let consumedResubmissionRequestId: bigint | null = null;
    if (existingBatch) {
      const gate = await evaluateOutcomeResubmissionGate({
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        reportType: parsed.data.reportType,
        stageKey: outcomeStageKey,
      });
      if (!gate.allowed) return void res.status(409).json({ error: gate.message, status: gate.status });
      consumedResubmissionRequestId = gate.requestEventId;
    }
    const outcomes = parsed.data.outcomes ?? [];

    // Type validation: every row's outcomeType must match the batch reportType (same rule the
    // CSV import enforces per row), otherwise a delete of this batch cannot scope cleanup safely.
    const mismatchedRows = outcomes.filter((o) => o.outcomeType !== parsed.data.reportType);
    if (mismatchedRows.length > 0) {
      return void res.status(422).json({
        error: "Outcome submission blocked: every row's outcome_type must match the batch report type.",
        details: {
          reportType: parsed.data.reportType,
          mismatchedOutcomeTypes: [...new Set(mismatchedRows.map((o) => o.outcomeType))],
          mismatchedCount: mismatchedRows.length,
        },
      });
    }

    // Enforce trainee scope: prevent uploading Cohort A rows into Cohort B report scope.
    const allSubmittedTraineeBigIds = [...new Set(outcomes.map((o) => String(o.traineeId)).filter((id) => /^\d+$/.test(id)))]
      .map((id) => BigInt(id));
    if (allSubmittedTraineeBigIds.length > 0) {
      const scopedTrainees = await prisma.trainee.findMany({
        where: {
          projectId,
          trainingProviderId,
          trainingId,
          rosterRole: TRACKED_ROSTER_WHERE,
          ...(effectiveCohortId ? { cohortId: effectiveCohortId } : {}),
          id: { in: allSubmittedTraineeBigIds },
        },
        select: { id: true, batchId: true },
      });
      const scopedSet = new Set(scopedTrainees.map((t) => t.id.toString()));
      const scopedBatchByTrainee = new Map(scopedTrainees.map((t) => [t.id.toString(), t.batchId]));
      const outOfScopeBigIds = allSubmittedTraineeBigIds.filter((x) => !scopedSet.has(x.toString()));
      if (outOfScopeBigIds.length > 0) {
        const outRows = await prisma.trainee.findMany({
          where: { projectId, trainingProviderId, id: { in: outOfScopeBigIds } },
          select: {
            id: true,
            traineeUniqueId: true,
            firstName: true,
            fatherName: true,
            grandfatherName: true,
            trainingId: true,
            cohortId: true,
            rosterRole: true,
          },
          take: 200,
        });
        return void res.status(422).json({
          error: "Outcome submission blocked: one or more trainees are not active in the selected training/cohort scope.",
          details: {
            outOfScopeCount: outOfScopeBigIds.length,
            outOfScopeTrainees: outRows.map((t) => ({
              traineeId: t.id.toString(),
              traineeUniqueId: t.traineeUniqueId,
              traineeName: [t.firstName, t.fatherName, t.grandfatherName].filter(Boolean).join(" "),
              actualTrainingId: t.trainingId?.toString() ?? null,
              actualCohortId: t.cohortId?.toString() ?? null,
              rosterRole: t.rosterRole,
            })),
          },
        });
      }
      const missingBatchIds = allSubmittedTraineeBigIds.filter((x) => scopedBatchByTrainee.get(x.toString()) == null);
      if (missingBatchIds.length > 0) {
        return void res.status(422).json({
          error: "Outcome submission blocked: one or more trainees are not linked to a delivery batch.",
          details: {
            missingBatchTraineeIds: missingBatchIds.slice(0, 100).map((x) => x.toString()),
            missingCount: missingBatchIds.length,
          },
        });
      }
      // Applies to EVERY report type, dropout included: outcomes may only be reported once the
      // class (delivery batch) has finished. Dropout used to be exempt here, which let a dropout
      // report be filed mid-class — at that point nobody is system-final yet, so the
      // attendance-based coverage check passed vacuously and was never re-run afterwards.
      const involvedBatchIds = [...new Set(scopedTrainees.map((t) => t.batchId).filter((x): x is bigint => x != null))];
      if (involvedBatchIds.length > 0) {
        const batches = await prisma.trainingBatch.findMany({
          where: { id: { in: involvedBatchIds }, projectId, trainingId, cohortId: effectiveCohortId ?? undefined },
          select: { id: true, code: true, name: true, endDate: true },
        });
        const today = dateOnlyUtc(new Date()).getTime();
        const unfinished = batches.filter((b) => dateOnlyUtc(b.endDate).getTime() > today);
        if (unfinished.length > 0) {
          return void res.status(422).json({
            error: "Outcome submission blocked: one or more rows belong to unfinished delivery batches.",
            details: unfinished.map((b) => ({
              batchId: b.id.toString(),
              batchLabel: `${b.code} - ${b.name}`,
              batchEndDate: b.endDate.toISOString().slice(0, 10),
            })),
          });
        }
      }
    }
    const requiresReportOrder: Record<string, string[]> = {
      completion: ["dropout"],
      certification: ["completion"],
      employment_placement: ["certification"],
      locality_compliant: ["employment_placement"],
      job_retention_3m: ["employment_placement"],
    };
    const requiredPrior = requiresReportOrder[parsed.data.reportType] ?? [];
    const INDICATOR_CODE_BY_OUTCOME_TYPE: Record<string, string> = {
      completion: "training_completion_rate",
      certification: "training_certification_rate",
      employment_placement: "employment_placement_rate",
      locality_compliant: "locality_compliant_placement_rate",
      job_retention_3m: "job_retention_3_month_rate",
      dropout: "trainee_dropout_rate",
    };
    const stageScopedOutcomeTypes = new Set(["employment_placement", "locality_compliant", "job_retention_3m"]);

    const outcomeTypesToResolve = [...new Set([...requiredPrior, parsed.data.reportType])].filter((t) => t in INDICATOR_CODE_BY_OUTCOME_TYPE);
    const stageIndicators = await prisma.projectIndicator.findMany({
      where: { projectId, code: { in: outcomeTypesToResolve.map((t) => INDICATOR_CODE_BY_OUTCOME_TYPE[t]!) } },
      select: { code: true, stages: { select: { stageKey: true, isFinalStage: true, sortOrder: true } } },
    });
    const finalStageKeyByOutcomeType = new Map<string, string | null>();
    for (const ot of outcomeTypesToResolve) {
      const ic = INDICATOR_CODE_BY_OUTCOME_TYPE[ot]!;
      const ind = stageIndicators.find((x) => x.code === ic);
      const stages = [...(ind?.stages ?? [])].sort((a, b) => a.sortOrder - b.sortOrder);
      const finalStage = stages.find((s) => s.isFinalStage) ?? stages[stages.length - 1];
      finalStageKeyByOutcomeType.set(ot, finalStage ? finalStage.stageKey : null);
    }
    const stageAwareOutcomeTypes = new Set<string>();
    for (const [ot, sk] of finalStageKeyByOutcomeType.entries()) {
      if (sk) stageAwareOutcomeTypes.add(ot);
    }
    const prereqStageKeyFor = (priorType: string): string | null => finalStageKeyByOutcomeType.get(priorType) ?? null;
    for (const priorType of requiredPrior) {
      const hasPriorBatch = await prisma.outcomeReportBatch.findFirst({
        where: {
          projectId,
          trainingProviderId,
          trainingId,
          cohortId: effectiveCohortId,
          reportType: priorType,
          status: "processed",
          ...(prereqStageKeyFor(priorType)
            ? { meta: { path: "$.stageKey", equals: prereqStageKeyFor(priorType) } as Prisma.JsonFilter }
            : {}),
        },
        select: { id: true },
      });
      if (!hasPriorBatch) {
        return void res.status(422).json({ error: `${parsed.data.reportType} submission is blocked until a processed ${priorType} report exists.` });
      }
    }

    const positiveRows = outcomes.filter((o) => o.reportedValue === true);
    const submittedTraineeIds = [...new Set(positiveRows.map((o) => String(o.traineeId)))];
    const submittedTraineeBigIds = submittedTraineeIds.filter((id) => /^\d+$/.test(id)).map((id) => BigInt(id));
    const existingPositives = submittedTraineeBigIds.length
      ? await prisma.traineeOutcome.findMany({
          where: {
            projectId,
            trainingProviderId,
            traineeId: { in: submittedTraineeBigIds },
            reportedValue: true,
          },
          select: { traineeId: true, outcomeType: true, meta: true },
        })
      : [];
    const existingByTrainee = new Map<string, Set<string>>();
    for (const row of existingPositives) {
      const key = row.traineeId.toString();
      if (!existingByTrainee.has(key)) existingByTrainee.set(key, new Set());
      const meta = row.meta && typeof row.meta === "object" && !Array.isArray(row.meta) ? (row.meta as Record<string, unknown>) : {};
      const sk = typeof meta.stageKey === "string" ? meta.stageKey : null;
      const ok = stageAwareOutcomeTypes.has(row.outcomeType) ? `${row.outcomeType}:${sk ?? "none"}` : row.outcomeType;
      existingByTrainee.get(key)!.add(ok);
    }
    const stagedByTrainee = new Map<string, Set<string>>();
    for (const row of positiveRows) {
      const key = String(row.traineeId);
      if (!stagedByTrainee.has(key)) stagedByTrainee.set(key, new Set());
      const meta = row.meta && typeof row.meta === "object" && !Array.isArray(row.meta) ? (row.meta as Record<string, unknown>) : {};
      const sk = typeof meta.stageKey === "string" ? meta.stageKey : null;
      const ok = stageAwareOutcomeTypes.has(row.outcomeType) ? `${row.outcomeType}:${sk ?? "none"}` : row.outcomeType;
      stagedByTrainee.get(key)!.add(ok);
    }
    const hasPositive = (traineeId: string, outcomeType: string, stageKey: string | null) => {
      const k = stageAwareOutcomeTypes.has(outcomeType) ? `${outcomeType}:${stageKey ?? "none"}` : outcomeType;
      return Boolean(existingByTrainee.get(traineeId)?.has(k) || stagedByTrainee.get(traineeId)?.has(k));
    };
    const contradictions: string[] = [];
    for (const row of positiveRows) {
      const tid = String(row.traineeId);
      const t = row.outcomeType;
      const meta = row.meta && typeof row.meta === "object" && !Array.isArray(row.meta) ? (row.meta as Record<string, unknown>) : {};
      const rowStageKey = typeof meta.stageKey === "string" ? meta.stageKey : null;
      if (["completion", "certification", "employment_placement", "locality_compliant", "job_retention_3m"].includes(t)) {
        if (hasPositive(tid, "dropout", null)) contradictions.push(`Trainee ${tid}: ${t} cannot be reported because dropout is already reported.`);
      }
      if (t === "certification" && !hasPositive(tid, "completion", prereqStageKeyFor("completion"))) {
        contradictions.push(`Trainee ${tid}: certification requires completion=true first.`);
      }
      if (t === "employment_placement" && !hasPositive(tid, "certification", prereqStageKeyFor("certification"))) {
        contradictions.push(`Trainee ${tid}: employment_placement requires certification=true first.`);
      }
      if ((t === "job_retention_3m" || t === "locality_compliant") && !hasPositive(tid, "employment_placement", prereqStageKeyFor("employment_placement") ?? rowStageKey)) {
        contradictions.push(`Trainee ${tid}: ${t} requires employment_placement=true first.`);
      }
      if (t === "dropout") {
        const incompatible = ["completion", "certification", "employment_placement", "locality_compliant", "job_retention_3m"];
        if (incompatible.some((code) => hasPositive(tid, code, rowStageKey))) {
          contradictions.push(`Trainee ${tid}: dropout cannot be reported after completion/certification/placement outcomes.`);
        }
      }
    }
    if (contradictions.length > 0) {
      return void res.status(422).json({
        error: "Outcome submission blocked due to business rule contradictions.",
        details: contradictions.slice(0, 20),
      });
    }

    if (parsed.data.reportType === PLACEMENT) {
      const problems: string[] = [];
      for (const o of outcomes) {
        if (o.outcomeType !== PLACEMENT) continue;
        if (o.reportedValue == null) {
          problems.push(`Trainee ${o.traineeId}: reported_value must be Y or N.`);
          continue;
        }
        const check = checkPlacement(o.reportedValue, (o.meta ?? {}) as Record<string, unknown>);
        if (check.problems.length > 0) problems.push(`Trainee ${o.traineeId}: ${check.problems.join(" ")}`);
        else o.meta = { ...check.clean, ...(outcomeStageKey ? { stageKey: outcomeStageKey } : {}) };
      }
      if (problems.length > 0) {
        return void res.status(422).json({ error: "Employment placement report blocked: one or more rows are invalid.", details: problems.slice(0, 50) });
      }
    }
    if (parsed.data.reportType === "dropout") {
      for (const o of outcomes) {
        if (o.outcomeType !== "dropout" || o.reportedValue !== true) continue;
        const meta = (o.meta ?? {}) as Record<string, unknown>;
        const reasonRaw = typeof meta.dropout_reason === "string" ? meta.dropout_reason : "";
        if (!String(reasonRaw).trim()) {
          return void res.status(422).json({ error: "Dropout report blocked: dropout_reason is required for reported dropout rows." });
        }
      }
      const projections = await computeDropoutProjections({
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
      });
      // POLICY: a system-final low-attendance trainee must come back as dropout=yes — an absent
      // row or an explicit N both block the report (see findSystemFinalDropoutViolations).
      const violations = findSystemFinalDropoutViolations(outcomes, projections);
      if (violations.length > 0) {
        return void res.status(422).json(systemFinalDropoutRejection(violations));
      }
    }
    const submittedTraineeBigIdsForWrite = [...new Set(outcomes.map((o) => String(o.traineeId)).filter((id) => /^\d+$/.test(id)))].map((id) => BigInt(id));
    const traineeBatchRows = submittedTraineeBigIdsForWrite.length
      ? await prisma.trainee.findMany({
          where: { id: { in: submittedTraineeBigIdsForWrite }, projectId, trainingProviderId },
          select: { id: true, batchId: true },
        })
      : [];
    const batchByTrainee = new Map(traineeBatchRows.map((t) => [t.id.toString(), t.batchId]));
    const rowsByBatch = new Map<string, Array<typeof outcomes[number] & { traineeIdBig: bigint; batchIdBig: bigint }>>();
    for (const o of outcomes) {
      const tid = BigInt(o.traineeId);
      const batchId = batchByTrainee.get(tid.toString()) ?? null;
      if (!batchByTrainee.has(tid.toString())) continue;
      if (batchId == null) continue;
      const key = batchId.toString();
      const arr = rowsByBatch.get(key) ?? [];
      arr.push({ ...o, traineeIdBig: tid, batchIdBig: batchId });
      rowsByBatch.set(key, arr);
    }
    if (parsed.data.reportType === "completion") {
      for (const batchIdKey of rowsByBatch.keys()) {
        const hasDropout = await prisma.outcomeReportBatch.findFirst({
          where: {
            projectId,
            trainingProviderId,
            trainingId,
            cohortId: effectiveCohortId,
            batchId: BigInt(batchIdKey),
            reportType: "dropout",
            status: "processed",
            ...(outcomeStageKey ? { meta: { path: "$.stageKey", equals: outcomeStageKey } as Prisma.JsonFilter } : {}),
          },
          select: { id: true },
        });
        if (!hasDropout) {
          return void res.status(422).json({
            error: "Completion report blocked: submit and process dropout report first for each included delivery batch.",
            details: { missingDropoutBatchId: batchIdKey },
          });
        }
      }
    }
    if (parsed.data.reportType === "completion" || parsed.data.reportType === "dropout") {
      for (const batchIdKey of rowsByBatch.keys()) {
        const coverage = await getAttendanceCoverageForOutcomeScope({
          projectId,
          trainingProviderId,
          trainingId,
          cohortId: effectiveCohortId,
          batchId: BigInt(batchIdKey),
        });
        if (coverage.expectedSlots > 0 && coverage.submittedRows < coverage.expectedSlots) {
          return void res.status(422).json({
            error: `${parsed.data.reportType === "dropout" ? "Dropout" : "Completion"} report blocked: attendance is incomplete for one or more included delivery batches.`,
            details: {
              batchId: batchIdKey,
              expectedAttendanceRows: coverage.expectedSlots,
              submittedAttendanceRows: coverage.submittedRows,
            },
          });
        }
      }
    }
    const createdBatchIds: string[] = [];
    for (const [batchIdKey, batchRows] of rowsByBatch.entries()) {
      const reportBatch = await prisma.outcomeReportBatch.create({
        data: {
          projectId,
          trainingProviderId,
          trainingId,
          cohortId: effectiveCohortId,
          batchId: BigInt(batchIdKey),
          reportType: parsed.data.reportType,
          sourceFilename: parsed.data.sourceFilename ?? null,
          status: batchRows.length ? "processed" : "uploaded",
          totalRows: batchRows.length,
          validRows: batchRows.length,
          invalidRows: 0,
          meta: outcomeStageKey ? ({ stageKey: outcomeStageKey } as Prisma.InputJsonValue) : undefined,
          uploadedByUserId: req.auth!.userId,
        },
      });
      createdBatchIds.push(reportBatch.id.toString());
      for (const o of batchRows) {
        await prisma.traineeOutcome.create({
          data: {
            projectId,
            trainingProviderId,
            trainingId,
            cohortId: effectiveCohortId,
            batchId: o.batchIdBig,
            traineeId: o.traineeIdBig,
            reportBatchId: reportBatch.id,
            outcomeType: o.outcomeType,
            statusDate: o.statusDate ? new Date(o.statusDate.slice(0, 10)) : null,
            reportedValue: o.reportedValue ?? null,
            meta: (() => {
              const m = ((o.meta ?? {}) as Record<string, unknown>) || {};
              if (outcomeStageKey) m.stageKey = outcomeStageKey;
              if (o.outcomeType === "dropout" && o.reportedValue === true) {
                m.dropout_reason = normalizeDropoutReason(typeof m.dropout_reason === "string" ? m.dropout_reason : null);
                m.source_type = "tp_reported";
              }
              return (Object.keys(m).length ? m : undefined) as Prisma.InputJsonValue | undefined;
            })(),
          },
        });
      }
    }
    await writeSubmissionEvent({
      projectId,
      trainingProviderId,
      trainingId,
      cohortId: effectiveCohortId,
      module: "outcomes",
      action: "batch_create",
      sourceType: "api",
      sourceRef: parsed.data.sourceFilename ?? null,
      payloadRaw: JSON.stringify(parsed.data),
      actorUserId: req.auth!.userId,
      meta: ({
        reportType: parsed.data.reportType,
        ...(outcomeStageKey ? { stageKey: outcomeStageKey } : {}),
      }) as Prisma.InputJsonValue,
    });
    if (consumedResubmissionRequestId) {
      await writeSubmissionEvent({
        projectId,
        trainingProviderId,
        trainingId,
        cohortId: effectiveCohortId,
        module: "outcomes",
        action: "resubmission_consumed",
        sourceType: "workflow",
        sourceRef: consumedResubmissionRequestId.toString(),
        actorUserId: req.auth!.userId,
        meta: {
          reportType: parsed.data.reportType,
          ...(outcomeStageKey ? { stageKey: outcomeStageKey } : {}),
        } as Prisma.InputJsonValue,
      });
    }
    res.status(201).json({ item: { id: createdBatchIds[0] ?? null, batchIds: createdBatchIds } });
  },
);

function normCsvHeader(s: string) {
  return s.trim().toLowerCase().replace(/\s+/g, "_");
}

function splitCsvLine(line: string): string[] {
  const out: string[] = [];
  let cur = "";
  let inQ = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"') {
      inQ = !inQ;
      continue;
    }
    if (!inQ && ch === ",") {
      out.push(cur.trim());
      cur = "";
      continue;
    }
    cur += ch;
  }
  out.push(cur.trim());
  return out.map((c) => c.replace(/^"|"$/g, ""));
}

function parseOutcomeBool(v: string): boolean | null {
  const t = v.trim().toLowerCase();
  if (t === "") return null;
  if (["1", "true", "yes", "y"].includes(t)) return true;
  if (["0", "false", "no", "n"].includes(t)) return false;
  return null;
}

function parseIsoDateCell(v: string | undefined): Date | null {
  if (!v?.trim()) return null;
  const d = new Date(v.trim().slice(0, 10));
  return Number.isNaN(d.getTime()) ? null : d;
}

function normalizeDropoutReason(v: string | null | undefined): string {
  const raw = String(v ?? "").trim().toLowerCase();
  if (!raw) return "other";
  if (raw.includes("voluntary")) return "voluntary_withdrawal";
  if (raw.includes("dismiss")) return "dismissal";
  if (raw.includes("attendance") || raw.includes("absen")) return "low_attendance_auto";
  if (raw.includes("health")) return "health";
  if (raw.includes("economic") || raw.includes("financial")) return "economic";
  if (raw.includes("migration") || raw.includes("relocat")) return "migration";
  if (raw.includes("withdraw")) return "voluntary_withdrawal";
  return "other";
}

/** Optional columns merged into trainee_outcomes.meta for outcome CSV rows. */
const CSV_OPTIONAL_ROW_META_KEYS = [
  "stage_key",
  "completion_date",
  "certification_date",
  "dropout_date",
  "dropout_reason",
  "dropout_notes",
  "employer_name",
  "employer_company",
  "employer_contact",
  "employer_phone",
  "employer_email",
  "salary",
  "salary_currency",
  "currency",
  "placement_address",
  "locality_address",
  "work_location",
  "job_title",
  "notes",
] as const;

function gatherCsvStringMeta(
  cols: string[],
  rowIdx: (names: string[]) => number,
  keys: readonly string[],
): Record<string, string> | undefined {
  const m: Record<string, string> = {};
  for (const key of keys) {
    const i = rowIdx([key]);
    if (i < 0) continue;
    const raw = cols[i]?.trim();
    if (raw) m[key] = raw;
  }
  return Object.keys(m).length > 0 ? m : undefined;
}

function metaJson(m: Record<string, string> | undefined): Prisma.InputJsonValue | undefined {
  if (!m || Object.keys(m).length === 0) return undefined;
  return m as Prisma.InputJsonValue;
}

router.post(
  "/projects/:projectId/outcome-batches/import-csv",
  requirePermission("submit:outcomes", { projectIdParam: "projectId" }),
  outcomeCsvUpload.single("file"),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const buf = req.file?.buffer;
    const originalName = req.file?.originalname ?? "upload.csv";
    if (!buf?.length) return void res.status(400).json({ error: "CSV file is required (field name: file)." });

    const reportType = String(req.body?.reportType ?? "").trim();
    if (!reportType) return void res.status(400).json({ error: "Form field reportType is required." });
    if (!isTpOutcomeCsvReportType(reportType)) {
      return void res.status(400).json({
        error: `Unknown reportType "${reportType}". Use one of: ${TP_OUTCOME_UPLOAD_ORDER.join(", ")}.`,
      });
    }

    let trainingProviderId = req.body?.trainingProviderId ? BigInt(String(req.body.trainingProviderId)) : null;
    if (scope.role === "tp") {
      if (!scope.providerId) return void res.status(403).json({ error: "No TP assignment." });
      trainingProviderId = scope.providerId;
    }
    if (!trainingProviderId) return void res.status(400).json({ error: "trainingProviderId required." });
    const providerId = trainingProviderId;
    const requestedTrainingId = req.body?.trainingId ? BigInt(String(req.body.trainingId)) : null;
    const requestedCohortId = req.body?.cohortId ? BigInt(String(req.body.cohortId)) : null;
    const outcomeStageKey = req.body?.stageKey ? String(req.body.stageKey).trim() : "";
    if (!requestedTrainingId) return void res.status(400).json({ error: "trainingId is required for outcome import." });
    const training = await prisma.training.findFirst({
      where: { id: requestedTrainingId, projectId, trainingProviderId: providerId },
      select: { id: true },
    });
    if (!training) return void res.status(404).json({ error: "Training not found for provider/project." });
    let effectiveCohortId: bigint | null = null;
    try {
      effectiveCohortId = await resolveCohortIdForTrainingDelivery({
        prisma,
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: requestedCohortId,
      });
    } catch (e: any) {
      return void res.status(e?.status ?? 400).json({ error: e?.message ?? "Invalid cohort." });
    }
    if (reportType === "completion") {
      const hasDropout = await ensureDropoutSubmittedBeforeCompletion({
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: effectiveCohortId,
        stageKey: outcomeStageKey || null,
      });
      if (!hasDropout) {
        return void res.status(422).json({
          error: "Completion import blocked: submit and process dropout report first for this scope.",
        });
      }
    }
    if (reportType === "completion" || reportType === "dropout") {
      const coverage = await getAttendanceCoverageForOutcomeScope({
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: effectiveCohortId,
      });
      if (coverage.expectedSlots > 0 && coverage.submittedRows < coverage.expectedSlots) {
        return void res.status(422).json({
          error: `${reportType === "dropout" ? "Dropout" : "Completion"} upload blocked: attendance is incomplete for this scope.`,
          details: {
            expectedAttendanceRows: coverage.expectedSlots,
            submittedAttendanceRows: coverage.submittedRows,
          },
        });
      }
    }
    const existingBatch = await prisma.outcomeReportBatch.findFirst({
      where: {
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: effectiveCohortId,
        reportType,
        status: "processed",
        ...(outcomeStageKey ? { meta: { path: "$.stageKey", equals: outcomeStageKey } as Prisma.JsonFilter } : {}),
      },
      select: { id: true },
    });
    let consumedResubmissionRequestId: bigint | null = null;
    if (existingBatch) {
      const gate = await evaluateOutcomeResubmissionGate({
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: effectiveCohortId,
        reportType,
        stageKey: outcomeStageKey || null,
      });
      if (!gate.allowed) return void res.status(409).json({ error: gate.message, status: gate.status });
      consumedResubmissionRequestId = gate.requestEventId;
    }

    const text = buf.toString("utf8");
    const lines = text.split(/\r?\n/).filter((l) => l.trim().length > 0);
    if (lines.length < 2) return void res.status(400).json({ error: "CSV must include a header row and at least one data row." });

    const header = splitCsvLine(lines[0]!).map(normCsvHeader);
    const idx = (names: string[]) => {
      for (const n of names) {
        const i = header.indexOf(normCsvHeader(n));
        if (i >= 0) return i;
      }
      return -1;
    };

    // Validate required columns against template definition
    const templateDef = OUTCOME_TEMPLATE_DEFS.find((d) => d.reportType === reportType);
    if (templateDef) {
      const missingRequired = templateDef.columns
        .filter((c) => c.required)
        .filter((c) => idx([c.key]) < 0)
        .map((c) => c.label);
      if (missingRequired.length > 0) {
        return void res.status(400).json({
          error: `CSV is missing required columns: ${missingRequired.join(", ")}.`,
        });
      }
    }

    type Staged = {
      traineeId: bigint;
      batchId: bigint;
      outcomeType: string;
      statusDate: Date | null;
      reportedValue: boolean | null;
      meta?: Prisma.InputJsonValue;
    };
    const staged: Staged[] = [];
    const rowErrors: string[] = [];
    const totalDataRows = lines.length - 1;

    async function resolveTraineeId(
      cols: string[],
      iTraineeId: number,
      iUnique: number,
      iExternal: number,
    ): Promise<{ traineeId: bigint | null; batchId: bigint | null; error?: string }> {
      let traineeId: bigint | null = null;
      const inputId = iTraineeId >= 0 ? (cols[iTraineeId] ?? "").trim() : "";
      const inputUid = iUnique >= 0 ? (cols[iUnique] ?? "").trim() : "";
      const inputExt = iExternal >= 0 ? (cols[iExternal] ?? "").trim() : "";
      if (iTraineeId >= 0 && cols[iTraineeId]?.trim()) {
        try {
          traineeId = BigInt(cols[iTraineeId]!.trim());
        } catch {
          traineeId = null;
        }
      }
      if (traineeId == null && iUnique >= 0 && cols[iUnique]?.trim()) {
        const tr = await prisma.trainee.findFirst({
          where: {
            projectId,
            trainingProviderId: providerId,
            traineeUniqueId: cols[iUnique]!.trim(),
            rosterRole: TRACKED_ROSTER_WHERE,
          },
          select: { id: true, traineeUniqueId: true, firstName: true, fatherName: true, grandfatherName: true, trainingId: true, cohortId: true },
        });
        traineeId = tr?.id ?? null;
      }
      if (traineeId == null && iExternal >= 0 && cols[iExternal]?.trim()) {
        const tr = await prisma.trainee.findFirst({
          where: {
            projectId,
            trainingProviderId: providerId,
            externalBeneficiaryId: cols[iExternal]!.trim(),
            rosterRole: TRACKED_ROSTER_WHERE,
          },
          select: { id: true, traineeUniqueId: true, firstName: true, fatherName: true, grandfatherName: true, trainingId: true, cohortId: true },
        });
        traineeId = tr?.id ?? null;
      }
      if (traineeId == null) {
        return {
          traineeId: null,
          batchId: null,
          error: `trainee not found for trainee_id='${inputId || "-"}' / trainee_unique_id='${inputUid || "-"}' / external_beneficiary_id='${inputExt || "-"}'`,
        };
      }
      const trOk = await prisma.trainee.findFirst({
        where: {
          id: traineeId,
          projectId,
          trainingProviderId: providerId,
          trainingId: requestedTrainingId,
          rosterRole: TRACKED_ROSTER_WHERE,
          ...(effectiveCohortId ? { cohortId: effectiveCohortId } : {}),
        },
        select: { id: true, batchId: true, traineeUniqueId: true, firstName: true, fatherName: true, grandfatherName: true, trainingId: true, cohortId: true },
      });
      if (trOk) return { traineeId, batchId: trOk.batchId ?? null };
      const trAnyScope = await prisma.trainee.findFirst({
        where: { id: traineeId, projectId, trainingProviderId: providerId },
        select: { id: true, traineeUniqueId: true, firstName: true, fatherName: true, grandfatherName: true, trainingId: true, cohortId: true, rosterRole: true },
      });
      if (trAnyScope) {
        const name = [trAnyScope.firstName, trAnyScope.fatherName, trAnyScope.grandfatherName].filter(Boolean).join(" ");
        return {
          traineeId: null,
          batchId: null,
          error: `${trAnyScope.traineeUniqueId} · ${name} is not an active trainee in selected scope (actual trainingId=${trAnyScope.trainingId?.toString() ?? "null"}, cohortId=${trAnyScope.cohortId?.toString() ?? "null"}, rosterRole=${trAnyScope.rosterRole})`,
        };
      }
      return { traineeId: null, batchId: null, error: `trainee ${traineeId.toString()} not found in provider scope` };
    }

    const iTraineeId = idx(["trainee_id", "traineeid"]);
    const iUnique = idx(["trainee_unique_id", "traineeuniqueid", "unique_id"]);
    const iExternal = idx([
      "external_beneficiary_id",
      "externalbeneficiaryid",
      "beneficiary_id",
      "provider_beneficiary_id",
    ]);
    const iType = idx(["outcome_type", "outcometype", "type"]);
    if (iType < 0) return void res.status(400).json({ error: "CSV must include an outcome_type column." });
    if (iTraineeId < 0 && iUnique < 0 && iExternal < 0) {
      return void res.status(400).json({
        error: "CSV must include trainee_id, trainee_unique_id, or external_beneficiary_id.",
      });
    }
    const iDate = idx(["status_date", "statusdate", "date"]);
    const iVal = idx(["reported_value", "reportedvalue", "value"]);
    const expectedOutcomeByReportType: Record<string, string> = {
      completion: "completion",
      certification: "certification",
      dropout: "dropout",
      employment_placement: "employment_placement",
      locality_compliant: "locality_compliant",
      job_retention_3m: "job_retention_3m",
    };
    const expectedOutcome = expectedOutcomeByReportType[reportType];

    for (let r = 1; r < lines.length; r++) {
      const cols = splitCsvLine(lines[r]!);
      let outcomeType = (cols[iType] ?? "").trim();
      if (!outcomeType) {
        rowErrors.push(`Row ${r + 1}: outcome_type is required.`);
        continue;
      }
      if (reportType === "job_retention_3m" && (outcomeType === "job_retention" || outcomeType === "job_retention_3m")) {
        outcomeType = "job_retention_3m";
      }
      if (expectedOutcome && outcomeType !== expectedOutcome) {
        rowErrors.push(`Row ${r + 1}: outcome_type must be '${expectedOutcome}' for this import.`);
        continue;
      }
      const traineeResolved = await resolveTraineeId(cols, iTraineeId, iUnique, iExternal);
      if (traineeResolved.traineeId == null) {
        rowErrors.push(`Row ${r + 1}: ${traineeResolved.error ?? "invalid trainee reference"}`);
        continue;
      }
      if (traineeResolved.batchId == null) {
        rowErrors.push(`Row ${r + 1}: trainee has no delivery batch assignment.`);
        continue;
      }
      const traineeId = traineeResolved.traineeId;
      const batchId = traineeResolved.batchId;
      let statusDate: Date | null = null;
      if (iDate >= 0 && cols[iDate]?.trim()) {
        statusDate = parseIsoDateCell(cols[iDate]);
      }
      if (!statusDate && outcomeType === "completion") {
        statusDate = parseIsoDateCell(cols[idx(["completion_date"])]);
      }
      if (!statusDate && outcomeType === "certification") {
        statusDate = parseIsoDateCell(cols[idx(["certification_date"])]);
      }
      if (!statusDate && outcomeType === "dropout") {
        statusDate = parseIsoDateCell(cols[idx(["dropout_date"])]);
      }
      const reportedValue = iVal >= 0 ? parseOutcomeBool(cols[iVal] ?? "") : null;
      const rowMeta = gatherCsvStringMeta(cols, idx, CSV_OPTIONAL_ROW_META_KEYS);
      if (rowMeta?.stage_key && !rowMeta.stageKey) {
        rowMeta.stageKey = rowMeta.stage_key;
      }
      if (outcomeType === "dropout" && reportedValue === true) {
        const reasonRaw = rowMeta?.dropout_reason ?? "";
        if (!String(reasonRaw).trim()) {
          rowErrors.push(`Row ${r + 1}: dropout_reason is required when dropout reported_value is true.`);
          continue;
        }
        if (rowMeta) {
          rowMeta.dropout_reason = normalizeDropoutReason(String(reasonRaw));
        }
      }
      let finalMeta = rowMeta;
      if (outcomeType === PLACEMENT) {
        if (reportedValue == null) {
          rowErrors.push(`Row ${r + 1}: reported_value must be Y (employed) or N (not employed).`);
          continue;
        }
        const check = checkPlacement(reportedValue, gatherCsvStringMeta(cols, idx, PLACEMENT_META_KEYS) ?? {});
        if (check.problems.length > 0) {
          rowErrors.push(`Row ${r + 1}: ${check.problems.join(" ")}`);
          continue;
        }
        finalMeta = Object.keys(check.clean).length > 0 ? check.clean : undefined;
      }
      if (outcomeStageKey) finalMeta = { ...(finalMeta ?? {}), stageKey: outcomeStageKey };
      staged.push({ traineeId, batchId, outcomeType, statusDate, reportedValue, meta: metaJson(finalMeta) });
    }

    if (rowErrors.length > 0) {
      return void res.status(422).json({
        error: "Outcome import blocked: one or more rows are invalid. No rows were committed.",
        details: rowErrors.slice(0, 200),
      });
    }
    // Applies to EVERY report type, dropout included (see the matching check in the submit path).
    const batchIds = [...new Set(staged.map((s) => s.batchId.toString()))].map((x) => BigInt(x));
    if (batchIds.length > 0) {
      const batches = await prisma.trainingBatch.findMany({
        where: { id: { in: batchIds }, projectId, trainingId: requestedTrainingId, cohortId: effectiveCohortId ?? undefined },
        select: { id: true, code: true, name: true, endDate: true },
      });
      const today = dateOnlyUtc(new Date()).getTime();
      const unfinished = batches.filter((b) => dateOnlyUtc(b.endDate).getTime() > today);
      if (unfinished.length > 0) {
        return void res.status(422).json({
          error: "Outcome import blocked: one or more rows belong to unfinished delivery batches.",
          details: unfinished.map((b) => ({
            batchId: b.id.toString(),
            batchLabel: `${b.code} - ${b.name}`,
            batchEndDate: b.endDate.toISOString().slice(0, 10),
          })),
        });
      }
    }

    const requiresReportOrder: Record<string, string[]> = {
      completion: ["dropout"],
      certification: ["completion"],
      employment_placement: ["certification"],
      locality_compliant: ["employment_placement"],
      job_retention_3m: ["employment_placement"],
    };
    const requiredPrior = requiresReportOrder[reportType] ?? [];
    const INDICATOR_CODE_BY_OUTCOME_TYPE: Record<string, string> = {
      completion: "training_completion_rate",
      certification: "training_certification_rate",
      employment_placement: "employment_placement_rate",
      locality_compliant: "locality_compliant_placement_rate",
      job_retention_3m: "job_retention_3_month_rate",
      dropout: "trainee_dropout_rate",
    };
    const outcomeTypesToResolve = [...new Set([...requiredPrior, reportType])].filter((t) => t in INDICATOR_CODE_BY_OUTCOME_TYPE);
    const stageIndicators = await prisma.projectIndicator.findMany({
      where: { projectId, code: { in: outcomeTypesToResolve.map((t) => INDICATOR_CODE_BY_OUTCOME_TYPE[t]!) } },
      select: { code: true, stages: { select: { stageKey: true, isFinalStage: true, sortOrder: true } } },
    });
    const finalStageKeyByOutcomeType = new Map<string, string | null>();
    for (const ot of outcomeTypesToResolve) {
      const ic = INDICATOR_CODE_BY_OUTCOME_TYPE[ot]!;
      const ind = stageIndicators.find((x) => x.code === ic);
      const stages = [...(ind?.stages ?? [])].sort((a, b) => a.sortOrder - b.sortOrder);
      const finalStage = stages.find((s) => s.isFinalStage) ?? stages[stages.length - 1];
      finalStageKeyByOutcomeType.set(ot, finalStage ? finalStage.stageKey : null);
    }
    const stageAwareOutcomeTypes = new Set<string>();
    for (const [ot, sk] of finalStageKeyByOutcomeType.entries()) {
      if (sk) stageAwareOutcomeTypes.add(ot);
    }
    const prereqStageKeyFor = (priorType: string): string | null => finalStageKeyByOutcomeType.get(priorType) ?? null;
    for (const priorType of requiredPrior) {
      const hasPriorBatch = await prisma.outcomeReportBatch.findFirst({
        where: {
          projectId,
          trainingProviderId: providerId,
          trainingId: requestedTrainingId,
          ...(effectiveCohortId ? { cohortId: effectiveCohortId } : { cohortId: null }),
          reportType: priorType,
          status: "processed",
          ...(prereqStageKeyFor(priorType)
            ? { meta: { path: "$.stageKey", equals: prereqStageKeyFor(priorType) } as Prisma.JsonFilter }
            : {}),
        },
        select: { id: true },
      });
      if (!hasPriorBatch) {
        return void res.status(422).json({ error: `${reportType} import is blocked until a processed ${priorType} report exists.` });
      }
    }

    const stagedByTrainee = new Map<string, Set<string>>();
    for (const s of staged) {
      if (s.reportedValue !== true) continue;
      const key = s.traineeId.toString();
      if (!stagedByTrainee.has(key)) stagedByTrainee.set(key, new Set());
      const rowMeta = s.meta && typeof s.meta === "object" && !Array.isArray(s.meta) ? (s.meta as Record<string, unknown>) : {};
      const rowStageKey = typeof rowMeta.stageKey === "string" ? rowMeta.stageKey : null;
      const outcomeKey = stageAwareOutcomeTypes.has(s.outcomeType) ? `${s.outcomeType}:${rowStageKey ?? "none"}` : s.outcomeType;
      stagedByTrainee.get(key)!.add(outcomeKey);
    }
    const stagedIds = [...new Set(staged.map((s) => s.traineeId.toString()))];
    const stagedBigIds = stagedIds.map((id) => BigInt(id));
    const existingPositives = await prisma.traineeOutcome.findMany({
      where: {
        projectId,
        trainingProviderId: providerId,
        traineeId: { in: stagedBigIds },
        reportedValue: true,
      },
      select: { traineeId: true, outcomeType: true, meta: true, reportBatch: { select: { id: true, sourceFilename: true } } },
    });
    const existingByTrainee = new Map<string, Set<string>>();
    const completionProof = new Map<string, string>();
    for (const row of existingPositives) {
      const key = row.traineeId.toString();
      if (!existingByTrainee.has(key)) existingByTrainee.set(key, new Set());
      // Stage-aware outcomes should be keyed by outcomeType+stageKey, but prerequisites like completion must be stage-agnostic.
      const meta = row.meta && typeof row.meta === "object" && !Array.isArray(row.meta) ? (row.meta as Record<string, unknown>) : {};
      const sk = typeof meta.stageKey === "string" ? meta.stageKey : null;
      const outcomeKey = stageAwareOutcomeTypes.has(row.outcomeType) ? `${row.outcomeType}:${sk ?? "none"}` : row.outcomeType;
      existingByTrainee.get(key)!.add(outcomeKey);
      if (row.outcomeType === "completion") {
        const proof = row.reportBatch?.sourceFilename
          ? `completion=true (batch ${row.reportBatch.id.toString()} · ${row.reportBatch.sourceFilename})`
          : row.reportBatch
          ? `completion=true (batch ${row.reportBatch.id.toString()})`
          : "completion=true";
        completionProof.set(key, proof);
      }
    }
    const hasPositive = (traineeId: string, outcomeType: string, stageKey: string | null) => {
      const k = stageAwareOutcomeTypes.has(outcomeType) ? `${outcomeType}:${stageKey ?? "none"}` : outcomeType;
      return Boolean(existingByTrainee.get(traineeId)?.has(k) || stagedByTrainee.get(traineeId)?.has(k));
    };
    const traineeInfo = await prisma.trainee.findMany({
      where: { id: { in: stagedBigIds } },
      select: { id: true, traineeUniqueId: true, firstName: true, fatherName: true, grandfatherName: true },
    });
    const traineeLabelById = new Map(
      traineeInfo.map((t) => [
        t.id.toString(),
        `${t.traineeUniqueId} · ${[t.firstName, t.fatherName, t.grandfatherName].filter(Boolean).join(" ")}`.trim(),
      ]),
    );
    const conflicts: string[] = [];
    for (const s of staged) {
      if (s.reportedValue !== true) continue;
      const tid = s.traineeId.toString();
      const t = s.outcomeType;
      const rowMeta = s.meta && typeof s.meta === "object" && !Array.isArray(s.meta) ? (s.meta as Record<string, unknown>) : {};
      const rowStageKey = typeof rowMeta.stageKey === "string" ? rowMeta.stageKey : null;
      const who = traineeLabelById.get(tid) ?? `Trainee ${tid}`;
      if (["completion", "certification", "employment_placement", "locality_compliant", "job_retention_3m"].includes(t)) {
        if (hasPositive(tid, "dropout", null)) conflicts.push(`${who}: ${t} cannot be reported because dropout is already reported.`);
      }
      if (t === "certification" && !hasPositive(tid, "completion", prereqStageKeyFor("completion"))) {
        const proof = completionProof.get(tid) ?? "completion=true not found";
        conflicts.push(`${who}: certification requires completion=true first (${proof}).`);
      }
      if (t === "employment_placement" && !hasPositive(tid, "certification", prereqStageKeyFor("certification"))) {
        conflicts.push(`${who}: employment_placement requires certification=true first.`);
      }
      if ((t === "job_retention_3m" || t === "locality_compliant") && !hasPositive(tid, "employment_placement", prereqStageKeyFor("employment_placement") ?? rowStageKey)) {
        conflicts.push(`${who}: ${t} requires employment_placement=true first.`);
      }
      if (t === "dropout") {
        const incompatible = ["completion", "certification", "employment_placement", "locality_compliant", "job_retention_3m"];
        if (incompatible.some((code) => hasPositive(tid, code, rowStageKey))) {
          conflicts.push(`${who}: dropout cannot be reported after completion/certification/placement outcomes.`);
        }
      }
    }
    if (conflicts.length > 0) {
      return void res.status(422).json({
        error: "Outcome import blocked due to business rule contradictions.",
        details: conflicts.slice(0, 20),
      });
    }

    const validRows = staged.length;
    const invalidRows = 0;
    let dropoutCoverageMeta: {
      requiredSystemFinal: number;
      missingFromTpReport: number;
      disputedCount: number;
    } | null = null;
    if (reportType === "dropout") {
      const projection = await computeDropoutProjections({
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: effectiveCohortId,
      });
      const requiredSystemFinal = projection.filter((p) => p.systemDropoutFinal).length;
      // POLICY: a system-final low-attendance trainee must come back as dropout=yes — an absent
      // row or an explicit N both block the report (see findSystemFinalDropoutViolations).
      const violations = findSystemFinalDropoutViolations(staged, projection);
      if (violations.length > 0) {
        return void res.status(422).json(systemFinalDropoutRejection(violations));
      }
      dropoutCoverageMeta = {
        requiredSystemFinal,
        // Every system-final trainee was reported Y (otherwise we would have returned above).
        missingFromTpReport: 0,
        disputedCount: 0,
      };
    }

    const rowsByBatch = new Map<string, Staged[]>();
    for (const row of staged) {
      const key = row.batchId.toString();
      const arr = rowsByBatch.get(key) ?? [];
      arr.push(row);
      rowsByBatch.set(key, arr);
    }
    if (reportType === "completion") {
      for (const batchIdKey of rowsByBatch.keys()) {
        const hasDropout = await prisma.outcomeReportBatch.findFirst({
          where: {
            projectId,
            trainingProviderId: providerId,
            trainingId: requestedTrainingId,
            cohortId: effectiveCohortId,
            batchId: BigInt(batchIdKey),
            reportType: "dropout",
            status: "processed",
            ...(outcomeStageKey ? { meta: { path: "$.stageKey", equals: outcomeStageKey } as Prisma.JsonFilter } : {}),
          },
          select: { id: true },
        });
        if (!hasDropout) {
          return void res.status(422).json({
            error: "Completion import blocked: submit and process dropout report first for each included delivery batch.",
            details: { missingDropoutBatchId: batchIdKey },
          });
        }
      }
    }
    if (reportType === "completion" || reportType === "dropout") {
      for (const batchIdKey of rowsByBatch.keys()) {
        const coverage = await getAttendanceCoverageForOutcomeScope({
          projectId,
          trainingProviderId: providerId,
          trainingId: requestedTrainingId,
          cohortId: effectiveCohortId,
          batchId: BigInt(batchIdKey),
        });
        if (coverage.expectedSlots > 0 && coverage.submittedRows < coverage.expectedSlots) {
          return void res.status(422).json({
            error: `${reportType === "dropout" ? "Dropout" : "Completion"} import blocked: attendance is incomplete for one or more included delivery batches.`,
            details: {
              batchId: batchIdKey,
              expectedAttendanceRows: coverage.expectedSlots,
              submittedAttendanceRows: coverage.submittedRows,
            },
          });
        }
      }
    }
    const createdBatchIds: string[] = [];
    for (const [batchIdKey, batchRows] of rowsByBatch.entries()) {
      const reportBatch = await prisma.outcomeReportBatch.create({
        data: {
          projectId,
          trainingProviderId: providerId,
          trainingId: requestedTrainingId,
          cohortId: effectiveCohortId,
          batchId: BigInt(batchIdKey),
          reportType,
          sourceFilename: originalName,
          status: batchRows.length > 0 ? "processed" : invalidRows > 0 ? "errors" : "uploaded",
          totalRows: batchRows.length,
          validRows: batchRows.length,
          invalidRows: 0,
          meta: outcomeStageKey ? ({ stageKey: outcomeStageKey } as Prisma.InputJsonValue) : undefined,
          uploadedByUserId: req.auth!.userId,
        },
      });
      createdBatchIds.push(reportBatch.id.toString());
      for (const o of batchRows) {
        const metaObj = ((o.meta ?? {}) as Record<string, unknown>) || {};
        if (outcomeStageKey) metaObj.stageKey = outcomeStageKey;
        if (o.outcomeType === "dropout" && o.reportedValue === true) {
          metaObj.dropout_reason = normalizeDropoutReason(typeof metaObj.dropout_reason === "string" ? metaObj.dropout_reason : null);
          metaObj.source_type = "tp_reported";
        }
        await prisma.traineeOutcome.create({
          data: {
            projectId,
            trainingProviderId: providerId,
            trainingId: requestedTrainingId,
            cohortId: effectiveCohortId,
            batchId: o.batchId,
            traineeId: o.traineeId,
            reportBatchId: reportBatch.id,
            outcomeType: o.outcomeType,
            statusDate: o.statusDate,
            reportedValue: o.reportedValue,
            meta: (Object.keys(metaObj).length ? metaObj : undefined) as Prisma.InputJsonValue | undefined,
          },
        });
      }
    }
    await writeSubmissionEvent({
      projectId,
      trainingProviderId: providerId,
      trainingId: requestedTrainingId,
      cohortId: effectiveCohortId,
      module: "outcomes",
      action: "import_csv",
      sourceType: "csv",
      sourceRef: originalName,
      payloadRaw: text,
      actorUserId: req.auth!.userId,
      meta: ({
        reportType,
        ...(outcomeStageKey ? { stageKey: outcomeStageKey } : {}),
        validRows,
        invalidRows,
        ...(dropoutCoverageMeta ? { dropoutCoverage: dropoutCoverageMeta } : {}),
      }) as Prisma.InputJsonValue,
    });
    if (consumedResubmissionRequestId) {
      await writeSubmissionEvent({
        projectId,
        trainingProviderId: providerId,
        trainingId: requestedTrainingId,
        cohortId: effectiveCohortId,
        module: "outcomes",
        action: "resubmission_consumed",
        sourceType: "workflow",
        sourceRef: consumedResubmissionRequestId.toString(),
        actorUserId: req.auth!.userId,
        meta: {
          reportType,
          ...(outcomeStageKey ? { stageKey: outcomeStageKey } : {}),
        } as Prisma.InputJsonValue,
      });
    }

    // Auto-backfill: retroactively update open pre-report verification runs
    try {
      const { autoBackfillVerificationRuns } = await import("../services/verificationDrawService.js");
      const backfillResult = await autoBackfillVerificationRuns(projectId, providerId, reportType, outcomeStageKey ?? null);
      if (backfillResult.runsProcessed > 0) {
        console.log(`[auto-backfill] reportType=${reportType} stageKey=${outcomeStageKey ?? "none"} — Processed ${backfillResult.runsProcessed} pre-report run(s): ${backfillResult.totalDropoutMarked} dropouts marked, ${backfillResult.totalClaimUpdated} claims updated.`);
      }
    } catch (err) {
      console.error("[auto-backfill] Failed to backfill verification runs:", err);
    }

    res.status(201).json({ item: { id: createdBatchIds[0] ?? null, batchIds: createdBatchIds }, validRows, invalidRows });
  },
);

router.get(
  "/projects/:projectId/dropout-projections",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    const trainingProviderId =
      scope.providerId ??
      (req.query.trainingProviderId && /^\d+$/.test(String(req.query.trainingProviderId))
        ? BigInt(String(req.query.trainingProviderId))
        : null);
    const trainingId =
      req.query.trainingId && /^\d+$/.test(String(req.query.trainingId))
        ? BigInt(String(req.query.trainingId))
        : null;
    const cohortId =
      req.query.cohortId && /^\d+$/.test(String(req.query.cohortId))
        ? BigInt(String(req.query.cohortId))
        : null;
    const traineeId =
      req.query.traineeId && /^\d+$/.test(String(req.query.traineeId))
        ? BigInt(String(req.query.traineeId))
        : null;
    const rowsRaw = await computeDropoutProjections({
      projectId,
      trainingProviderId,
      trainingId,
      cohortId,
      traineeId,
    });
    const [contractByTp, registeredByTp] = await Promise.all([
      contractTargetsByTp(prisma, projectId),
      registeredTraineesByTp(prisma, projectId),
    ]);
    const rows = enrichDropoutProjectionsWithKpiBuffer(rowsRaw, contractByTp, registeredByTp);
    const reasonShares = summarizeReasonShares(rows, { forKpiRate: true }).shares;
    const summary = buildDropoutProjectionApiSummary(rows, contractByTp, registeredByTp, reasonShares);

    // Compute attendance coverage to determine if all sessions (current + future) are covered.
    let allSessionsCovered = true;
    if (trainingId && trainingProviderId) {
      try {
        const coverage = await computeAttendanceCoverageForTrainingScope({
          projectId,
          trainingProviderId,
          trainingId,
          cohortId: cohortId ?? null,
          batchId: null,
        });
        allSessionsCovered = coverage.sessionDaysDue > 0 && coverage.sessionDaysSubmitted >= coverage.sessionDaysDue;
      } catch {
        allSessionsCovered = false;
      }
    }

    res.json({
      summary,
      allSessionsCovered,
      items: rows.map((r) => ({
        traineeId: asId(r.traineeId),
        traineeUniqueId: r.traineeUniqueId,
        traineeName: r.traineeName,
        trainingProviderId: asId(r.trainingProviderId),
        trainingId: asId(r.trainingId),
        cohortId: r.cohortId ? asId(r.cohortId) : null,
        possibleToDate: r.possibleToDate,
        presentToDate: r.presentToDate,
        attendancePctToDate: r.attendancePctToDate,
        attendancePctFinal: r.attendancePctFinal,
        maxRecoverablePct: r.maxRecoverablePct,
        systemDropoutRisk: r.systemDropoutRisk,
        systemDropoutFinal: r.systemDropoutFinal,
        tpReportedDropout: r.tpReportedDropout,
        effectiveDropout: r.effectiveDropout,
        countsTowardKpiRate: r.countsTowardKpiRate,
        reasonCode: r.reasonCode,
        reasonSource: r.reasonSource,
        missingInTpReport: r.missingInTpReport,
      })),
    });
  },
);

router.get(
  "/projects/:projectId/trainee-outcomes",
  requirePermission("view:trainees", { projectIdParam: "projectId" }),
  async (req: AuthedRequest, res) => {
    const projectId = BigInt(req.params.projectId);
    const traineeId = req.query.traineeId ? BigInt(String(req.query.traineeId)) : null;
    const reportType = req.query.reportType ? String(req.query.reportType).trim() : null;
    const trainingId =
      req.query.trainingId && /^\d+$/.test(String(req.query.trainingId))
        ? BigInt(String(req.query.trainingId))
        : null;
    const cohortId =
      req.query.cohortId && /^\d+$/.test(String(req.query.cohortId))
        ? BigInt(String(req.query.cohortId))
        : null;
    const stageKey =
      typeof req.query.stageKey === "string" && req.query.stageKey.trim().length > 0
        ? req.query.stageKey.trim()
        : null;
    const requestedProviderId =
      req.query.trainingProviderId && /^\d+$/.test(String(req.query.trainingProviderId))
        ? BigInt(String(req.query.trainingProviderId))
        : null;
    if (!(await hasProjectAccess(projectId, req.auth!.userId))) return void res.status(403).json({ error: "No access." });
    const scope = await resolveScope(projectId, req.auth!.userId);
    if (scope.providerId && requestedProviderId && scope.providerId !== requestedProviderId) {
      return void res.status(403).json({ error: "No access to this provider." });
    }
    const providerFilter = scope.providerId
      ? { trainingProviderId: scope.providerId }
      : requestedProviderId
        ? { trainingProviderId: requestedProviderId }
        : {};
    const items = await prisma.traineeOutcome.findMany({
      where: {
        projectId,
        ...providerFilter,
        ...(trainingId ? { trainingId } : {}),
        ...(cohortId ? { cohortId } : {}),
        ...(traineeId ? { traineeId } : {}),
        ...(reportType ? { outcomeType: reportType } : {}),
        ...(stageKey ? { meta: { path: "$.stageKey", equals: stageKey } as Prisma.JsonFilter } : {}),
      },
      orderBy: { id: "desc" },
      take: traineeId ? 500 : 2000,
      include: {
        trainee: {
          select: {
            id: true,
            traineeUniqueId: true,
            firstName: true,
            fatherName: true,
            grandfatherName: true,
          },
        },
        reportBatch: {
          select: {
            id: true,
            sourceFilename: true,
            reportType: true,
          },
        },
      },
    });
    res.json({
      items: items.map((o) => ({
        id: asId(o.id),
        traineeId: asId(o.traineeId),
        traineeUniqueId: o.trainee.traineeUniqueId,
        traineeName: [o.trainee.firstName, o.trainee.fatherName, o.trainee.grandfatherName]
          .filter((x) => Boolean(x && String(x).trim()))
          .join(" "),
        outcomeType: o.outcomeType,
        statusDate: o.statusDate?.toISOString().slice(0, 10) ?? null,
        reportedValue: o.reportedValue,
        meta: o.meta,
        trainingId: o.trainingId ? asId(o.trainingId) : null,
        cohortId: o.cohortId ? asId(o.cohortId) : null,
        reportBatchId: o.reportBatchId ? asId(o.reportBatchId) : null,
        reportBatchType: o.reportBatch?.reportType ?? null,
        stageKey:
          o.meta && typeof o.meta === "object" && !Array.isArray(o.meta) && typeof (o.meta as Record<string, unknown>).stageKey === "string"
            ? ((o.meta as Record<string, unknown>).stageKey as string)
            : null,
        sourceFilename: o.reportBatch?.sourceFilename ?? null,
      })),
    });
  },
);

/** Seed global variables + default protocol activities/indicators for a project (M&E admin). */
router.post(
  "/projects/:projectId/performance/seed-catalog",
  requirePermission("manage:indicators", { 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." });

    await prisma.projectIndicator.deleteMany({
      where: { projectId, code: { in: [...OBSOLETE_PROJECT_INDICATOR_CODES] } },
    });
    await prisma.indicatorVariable.deleteMany({
      where: { code: { in: [...OBSOLETE_INDICATOR_VARIABLE_CODES] } },
    });

    for (const v of SEED_VARIABLES) {
      const spec = v.querySpec as Prisma.InputJsonValue;
      await prisma.indicatorVariable.upsert({
        where: { code: v.code },
        create: { code: v.code, name: v.name, description: v.description, querySpec: spec, isActive: true },
        update: { name: v.name, description: v.description, querySpec: spec },
      });
    }

    for (const a of SEED_ACTIVITIES) {
      await (prisma.projectActivity as any).upsert({
        where: { projectId_code: { projectId, code: a.code } },
        create: {
          projectId,
          code: a.code,
          name: a.name,
          description: a.description,
          submissionScope: a.submissionScope ?? "delivery",
          sortOrder: a.sortOrder,
        },
        update: { name: a.name, description: a.description, submissionScope: a.submissionScope ?? "delivery", sortOrder: a.sortOrder },
      });
    }

    const activities = await prisma.projectActivity.findMany({ where: { projectId } });
    const providers = await prisma.trainingProvider.findMany({ where: { projectId }, select: { id: true } });
    for (const act of activities) {
      const existingAssignments = await (prisma.projectActivityAssignment as any).count({
        where: { projectId, projectActivityId: act.id },
      });
      if (existingAssignments === 0 && providers.length > 0) {
        await (prisma.projectActivityAssignment as any).createMany({
          data: providers.map((p) => ({
            projectId,
            projectActivityId: act.id,
            trainingProviderId: p.id,
          })),
        });
      }
      // Duration-specific rules are now required; no fallback rule is auto-seeded.
    }

    for (const ind of SEED_INDICATORS) {
      await prisma.projectIndicator.upsert({
        where: { projectId_code: { projectId, code: ind.code } },
        create: {
          projectId,
          code: ind.code,
          name: ind.name,
          description: ind.description ?? null,
          unit: ind.computationMode === "count" ? "#" : "%",
          computationMode: ind.computationMode,
          claimMode: ind.claimMode,
          verificationMode: ind.verificationMode,
          thresholdValue: ind.threshold,
          protocolOrder: ind.order,
          monitoringNumeratorVariable: ind.monNum,
          monitoringDenominatorVariable: ind.monDen,
          verificationNumeratorVariable: ind.verNum,
          verificationDenominatorVariable: ind.verDen,
          isActive: true,
        },
        update: {
          name: ind.name,
          description: ind.description ?? null,
          unit: ind.computationMode === "count" ? "#" : "%",
          computationMode: ind.computationMode,
          claimMode: ind.claimMode,
          verificationMode: ind.verificationMode,
          thresholdValue: ind.threshold,
          protocolOrder: ind.order,
          monitoringNumeratorVariable: ind.monNum,
          monitoringDenominatorVariable: ind.monDen,
          verificationNumeratorVariable: ind.verNum,
          verificationDenominatorVariable: ind.verDen,
        },
      });
    }
    res.json({
      ok: true,
      seeded: {
        indicatorVariables: SEED_VARIABLES.length,
        projectActivities: SEED_ACTIVITIES.length,
        activityRules: activities.length,
        projectIndicators: SEED_INDICATORS.length,
      },
    });
  },
);

export default router;
