import { prisma } from "../prisma.js";
import { writeAuditEvent } from "./auditEventService.js";

/** Plain JSON copy (BigInt and Decimal become strings) so it can be kept in the audit log. */
function plain<T>(v: T): unknown {
  return JSON.parse(JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x)));
}

const day = (d: Date) => d.toISOString().slice(0, 10).split("-").reverse().join("/");

async function loadAll(projectId: bigint, traineeId: bigint) {
  const trainee = await prisma.trainee.findFirst({ where: { id: traineeId, projectId } });
  if (!trainee) return null;
  const where = { traineeId };
  const [enrollments, attendance, outcomes, subjects, runDropouts, duplicates] = await Promise.all([
    prisma.traineeEnrollment.findMany({ where }),
    prisma.traineeAttendanceDay.findMany({ where, orderBy: { sessionDate: "asc" } }),
    prisma.traineeOutcome.findMany({ where, orderBy: { id: "asc" } }),
    prisma.verificationSampleSubject.findMany({
      where,
      include: { evidences: true, run: { select: { id: true, indicatorCode: true, status: true, roundNo: true } } },
    }),
    prisma.verificationSampleRunDropout.findMany({ where }),
    prisma.traineeDuplicateCandidate.findMany({ where: { OR: [{ traineeAId: traineeId }, { traineeBId: traineeId }] } }),
  ]);
  const replacedBy = await prisma.trainee.findMany({ where: { replacesTraineeId: traineeId }, select: { id: true, traineeUniqueId: true } });
  return { trainee, enrollments, attendance, outcomes, subjects, runDropouts, duplicates, replacedBy };
}

/** Where the trainee appears; shown before deleting. */
export async function traineeDeleteImpact(projectId: bigint, traineeId: bigint) {
  const all = await loadAll(projectId, traineeId);
  if (!all) return null;
  const { trainee, enrollments, attendance, outcomes, subjects, runDropouts, duplicates, replacedBy } = all;
  const items: Array<{ area: string; detail: string[] }> = [];
  const warnings: string[] = [];
  items.push({
    area: "Trainee record",
    detail: [`${trainee.traineeUniqueId ?? trainee.id} · ${[trainee.firstName, trainee.fatherName, trainee.grandfatherName].filter(Boolean).join(" ")}`],
  });
  if (enrollments.length) items.push({ area: "Class enrolment", detail: [`${enrollments.length} enrolment record(s)`] });
  if (attendance.length) {
    const present = attendance.filter((a) => a.status === "present").length;
    items.push({
      area: "Attendance",
      detail: [`${attendance.length} day(s) marked (${present} present), ${day(attendance[0].sessionDate)} to ${day(attendance[attendance.length - 1].sessionDate)}`],
    });
  }
  if (outcomes.length) {
    const byType = new Map<string, number>();
    for (const o of outcomes) byType.set(o.outcomeType, (byType.get(o.outcomeType) ?? 0) + 1);
    items.push({ area: "Outcome reports", detail: [...byType].map(([t, n]) => `${t}: ${n} line(s)`) });
  }
  if (subjects.length) {
    items.push({
      area: "Verification samples",
      detail: subjects.map(
        (s) =>
          `${s.run.indicatorCode} round ${s.run.roundNo} (${s.run.status}) · ${s.subjectRole}` +
          (s.verifiedValue == null ? " · not verified yet" : ` · verified ${s.verifiedValue ? "Yes" : "No"}`) +
          (s.evidences.length ? ` · ${s.evidences.length} evidence record(s)` : ""),
      ),
    });
    if (subjects.some((s) => s.verifiedValue != null)) warnings.push("This trainee was already verified in a sample. The verification result will be removed from that sample.");
    if (subjects.some((s) => s.run.status === "finalized")) warnings.push("This trainee is in a finalized sample. The finalized figures will no longer match the sample list.");
  }
  if (runDropouts.length) items.push({ area: "Sample dropout lists", detail: [`${runDropouts.length} sample(s)`] });
  if (duplicates.length) items.push({ area: "Duplicate checks", detail: [`${duplicates.length} possible-duplicate pair(s)`] });
  if (replacedBy.length) items.push({ area: "Replacements", detail: replacedBy.map((r) => `${r.traineeUniqueId ?? r.id} will no longer point to this trainee`) });
  return {
    code: trainee.traineeUniqueId ?? String(trainee.id),
    sampled: subjects.length > 0,
    warnings,
    items,
  };
}

/** Deletes the trainee and everything linked (database cascades), after keeping a full copy in the audit log. */
export async function deleteTraineeWithCopy(args: { projectId: bigint; traineeId: bigint; reason: string; actorUserId: bigint }) {
  const all = await loadAll(args.projectId, args.traineeId);
  if (!all) return null;
  const t = all.trainee;
  const scope = { projectId: args.projectId, trainingProviderId: t.trainingProviderId, trainingId: t.trainingId, cohortId: t.cohortId, batchId: t.batchId };
  // Copy first: if the delete fails, a second event says so; the data is never removed without a copy.
  await writeAuditEvent({
    ...scope,
    module: "domain",
    action: "trainee_deleted",
    sourceType: "trainee",
    sourceRef: t.id.toString(),
    meta: { reason: args.reason, code: t.traineeUniqueId, removed: plain(all) } as never,
    actorUserId: args.actorUserId,
  });
  try {
    await prisma.trainee.delete({ where: { id: t.id } });
  } catch (e) {
    await writeAuditEvent({ ...scope, module: "domain", action: "trainee_delete_failed", sourceType: "trainee", sourceRef: t.id.toString(), actorUserId: args.actorUserId });
    throw e;
  }
  return { code: t.traineeUniqueId };
}
