/**
 * Links outcome CSV report types to project indicators that use trainee-roster / outcome data.
 * Used to label upload templates with the indicators TPs are satisfying.
 */
import type { PrismaClient } from "@prisma/client";
import { outcomeTemplatesForTpUpload, type OutcomeTemplateDef } from "./outcomeTemplateCatalog.js";

/** Maps each TP upload `reportType` to protocol indicator codes that depend on that upload. */
export const ROSTER_REPORT_TYPE_TO_INDICATOR_CODES: Record<string, string[]> = {
  completion: ["training_completion_rate"],
  certification: ["training_certification_rate"],
  dropout: ["trainee_dropout_rate"],
  employment_placement: ["employment_placement_rate"],
  locality_compliant: ["locality_compliant_placement_rate"],
  job_retention_3m: ["job_retention_3_month_rate"],
};

export type OutcomeTemplateWithRoster = OutcomeTemplateDef & {
  /** Project indicators (trainee_roster) that this report type feeds; empty if none configured. */
  rosterIndicators: Array<{ code: string; name: string }>;
};

export async function getOutcomeTemplatesForProject(
  prisma: PrismaClient,
  projectId: bigint,
): Promise<OutcomeTemplateWithRoster[]> {
  const defs = outcomeTemplatesForTpUpload();
  const indicators = await prisma.projectIndicator.findMany({
    where: { projectId, isActive: true, claimMode: "trainee_roster" },
  });
  const byCode = new Map(indicators.map((i) => [i.code, i]));

  return defs.map((def) => {
    const codes = ROSTER_REPORT_TYPE_TO_INDICATOR_CODES[def.reportType] ?? [];
    const rosterIndicators = codes
      .map((c) => {
        const ind = byCode.get(c);
        return ind ? { code: ind.code, name: ind.name } : null;
      })
      .filter((x): x is { code: string; name: string } => Boolean(x));
    return { ...def, rosterIndicators };
  });
}
