import type { DropoutProjectionRow } from "./dropoutProtocol.js";

/**
 * POLICY — low-attendance dropouts must be reported as dropout=yes.
 *
 * Attendance is owned by the training provider, so once the system has finalised a trainee as a
 * low-attendance dropout (attendance < 80% after the class ended, transfers excluded) that
 * trainee MUST come back in the dropout report as reported_value=Y. A row that is absent, or one
 * that is explicitly reported as N, both block the report — there is no dispute path any more.
 * The caller turns the returned list into a 422.
 */

export type SystemFinalDropoutViolation = {
  traineeId: string;
  traineeUniqueId: string;
  traineeName: string;
  attendancePctFinal: number;
  /** `missing` — no dropout row at all. `reported_no` — row present but reported N. */
  issue: "missing" | "reported_no";
};

export type DropoutReportRow = {
  traineeId: string | bigint;
  outcomeType: string;
  reportedValue?: boolean | null;
};

/**
 * Returns one entry per system-final (attendance < 80% after the class ended) trainee that the
 * submission does NOT report as dropout=yes.
 *
 * `submitted` is the rows the provider is trying to write, for either the API submit path
 * (`traineeId: string`) or the CSV import path (`traineeId: bigint`).
 */
export function findSystemFinalDropoutViolations(
  submitted: DropoutReportRow[],
  projections: DropoutProjectionRow[],
): SystemFinalDropoutViolation[] {
  const reportedYes = new Set(
    submitted
      .filter((o) => o.outcomeType === "dropout" && o.reportedValue === true)
      .map((o) => String(o.traineeId)),
  );
  const reportedNo = new Set(
    submitted
      .filter((o) => o.outcomeType === "dropout" && o.reportedValue === false)
      .map((o) => String(o.traineeId)),
  );

  const violations: SystemFinalDropoutViolation[] = [];
  for (const p of projections) {
    if (!p.systemDropoutFinal) continue;
    const id = p.traineeId.toString();
    if (reportedYes.has(id)) continue;
    violations.push({
      traineeId: id,
      traineeUniqueId: p.traineeUniqueId,
      traineeName: p.traineeName,
      attendancePctFinal: p.attendancePctFinal,
      issue: reportedNo.has(id) ? "reported_no" : "missing",
    });
  }
  return violations;
}

/** 422 payload shared by the submit and import paths so both reject identically. */
export function systemFinalDropoutRejection(violations: SystemFinalDropoutViolation[]) {
  const missing = violations.filter((v) => v.issue === "missing");
  const reportedNo = violations.filter((v) => v.issue === "reported_no");
  return {
    error:
      "Dropout report blocked: every trainee the system has flagged as a low-attendance dropout " +
      "must be reported as dropout=yes. Report them as Y, or correct their attendance first.",
    details: {
      missingCount: missing.length,
      reportedNoCount: reportedNo.length,
      totalCount: violations.length,
      trainees: violations.slice(0, 100),
    },
  };
}
