import { SUPPORT } from "./services/placementRules.js";
/** Static catalogue for TP outcome CSV templates (headers + guidance). */

export type TemplateColumnKind = "identifier" | "boolean" | "date" | "text";

export type TemplateColumn = {
  key: string;
  label: string;
  kind: TemplateColumnKind;
  required: boolean;
  /** Plain-language hint for TPs (allowed values, format). */
  hint: string;
};

export type OutcomeTemplateDef = {
  reportType: string;
  title: string;
  summary: string;
  /** Longer description shown in the UI. */
  guidance: string;
  columns: TemplateColumn[];
};

const EXTERNAL_BENEFICIARY_ID_COLUMN: TemplateColumn = {
  key: "external_beneficiary_id",
  label: "External beneficiary ID",
  kind: "identifier",
  required: false,
  hint: "Provider-issued ID (e.g. Qiyas). Import matches this or trainee_unique_id when either is filled.",
};

function withExternalBeneficiaryColumn(columns: TemplateColumn[]): TemplateColumn[] {
  if (columns.some((c) => c.key === "external_beneficiary_id")) return columns;
  return [EXTERNAL_BENEFICIARY_ID_COLUMN, ...columns];
}

const SUPPORT_LABELS: Record<(typeof SUPPORT)[number], string> = {
  placement_support_outreach_referrals: "Outreach / referrals",
  placement_support_job_fair: "Job fair",
  placement_support_interview_prep: "Interview preparation",
  placement_support_cv_writing: "CV writing",
  placement_support_direct_placement: "Direct placement",
  placement_support_job_matching: "Job matching",
  placement_support_employer_followup: "Employer follow-up",
};
const PLACEMENT_SUPPORT_COLUMNS: TemplateColumn[] = SUPPORT.map((key) => ({
  key,
  label: `Support: ${SUPPORT_LABELS[key]}`,
  kind: "boolean",
  required: true,
  hint: "Yes or No, for every row.",
}));

const OUTCOME_TEMPLATE_DEFS_RAW: OutcomeTemplateDef[] = [
  {
    reportType: "employment_placement",
    title: "Employment placement",
    summary: "One row per certified trainee: employed or not, the placement support given, and the job details.",
    guidance:
      "Replaces the old job linkage and decent job reports. Only trainees with certification = Y are listed. reported_value Y = employed in any form, N = not employed. Every row answers the 7 placement_support_* columns with Yes or No. When reported_value is N, leave all job columns empty. When Y, fill employment_type (wage_employed, self_employed_business, self_employed_freelance, other) and the columns it needs: wage_employed needs job_title, employment_start_date, monthly_income_etb, contract_type, employer_name, employer_contact_person and the employer's phone or email; self-employed needs employment_start_date, monthly_income_etb, legal_form and has_business_license; other needs employment_type_other_text, employment_start_date and monthly_income_etb. Dates are DD/MM/YYYY (day first). Due 60 days after the class ends.",
    columns: [
      { key: "trainee_unique_id", label: "Trainee unique ID", kind: "identifier", required: true, hint: "Must match the trainee_unique_id already imported for your provider in this project." },
      { key: "trainee_name", label: "Trainee name", kind: "text", required: false, hint: "Helper column; import matches on trainee_unique_id." },
      { key: "outcome_type", label: "Outcome type", kind: "text", required: true, hint: "employment_placement" },
      { key: "reported_value", label: "Employed", kind: "boolean", required: true, hint: "Y = employed in any form, N = not employed." },
      { key: "status_date", label: "Status date", kind: "date", required: false, hint: "Optional. DD/MM/YYYY." },
      ...PLACEMENT_SUPPORT_COLUMNS,
      { key: "employment_type", label: "Employment type", kind: "text", required: false, hint: "When employed: wage_employed, self_employed_business, self_employed_freelance or other." },
      { key: "employment_type_other_text", label: "Employment type (other)", kind: "text", required: false, hint: "Only when employment_type is other." },
      { key: "job_title", label: "Job title", kind: "text", required: false, hint: "Required for wage_employed." },
      { key: "employment_start_date", label: "Employment start date", kind: "date", required: false, hint: "When employed. DD/MM/YYYY (day first), not in the future." },
      { key: "monthly_income_etb", label: "Monthly income (ETB)", kind: "text", required: false, hint: "When employed. A number above 0, no commas or text." },
      { key: "contract_type", label: "Contract type", kind: "text", required: false, hint: "wage_employed: full_time_permanent, contract_under_12_months, contract_12_months_or_more or other." },
      { key: "contract_type_other_text", label: "Contract type (other)", kind: "text", required: false, hint: "Only when contract_type is other." },
      { key: "employer_name", label: "Employer name", kind: "text", required: false, hint: "Required for wage_employed." },
      { key: "employer_contact_person", label: "Employer contact person", kind: "text", required: false, hint: "Required for wage_employed." },
      { key: "employer_contact_position", label: "Contact person position", kind: "text", required: false, hint: "Optional, wage_employed only." },
      { key: "employer_email", label: "Employer email", kind: "text", required: false, hint: "wage_employed: give email or phone." },
      { key: "employer_phone", label: "Employer phone", kind: "text", required: false, hint: "wage_employed: give email or phone." },
      { key: "legal_form", label: "Legal form", kind: "text", required: false, hint: "Self-employed: sole_proprietorship, partnership, plc, no_legal_form or other." },
      { key: "legal_form_other_text", label: "Legal form (other)", kind: "text", required: false, hint: "Only when legal_form is other." },
      { key: "has_business_license", label: "Has business licence", kind: "boolean", required: false, hint: "Self-employed: Yes or No." },
      { key: "notes", label: "Notes", kind: "text", required: false, hint: "Any extra free-text context for this row." },
    ],
  },
  {
    reportType: "locality_compliant",
    title: "Locality compliant placement",
    summary: "One row per trainee outcome row: mark locality compliance status.",
    guidance: "Use outcome_type locality_compliant, reported_value Y/N, optional status_date, and locality address.",
    columns: [
      {
        key: "trainee_unique_id",
        label: "Trainee unique ID",
        kind: "identifier",
        required: true,
        hint: "Must match the trainee_unique_id already imported for your provider in this project.",
      },
      {
        key: "trainee_name",
        label: "Trainee name",
        kind: "text",
        required: false,
        hint: "Optional helper column for review; import uses trainee_unique_id / trainee_id for matching.",
      },
      {
        key: "outcome_type",
        label: "Outcome type",
        kind: "text",
        required: true,
        hint: "locality_compliant",
      },
      {
        key: "reported_value",
        label: "Locality compliant",
        kind: "boolean",
        required: false,
        hint: "Y/N",
      },
      {
        key: "status_date",
        label: "Status date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD",
      },
      {
        key: "locality_address",
        label: "Locality / residence address",
        kind: "text",
        required: false,
        hint: "Address used to validate locality compliance.",
      },
      {
        key: "notes",
        label: "Notes",
        kind: "text",
        required: false,
        hint: "Any extra free-text context for this row.",
      },
    ],
  },
  {
    reportType: "completion",
    title: "Training completion",
    summary: "One row per trainee outcome row: mark completion status.",
    guidance:
      "Use trainee_unique_id or trainee_id plus outcome_type \"completion\" (or select this template and use the standard columns). reported_value is Y/N for completed.",
    columns: [
      {
        key: "trainee_unique_id",
        label: "Trainee unique ID",
        kind: "identifier",
        required: true,
        hint: "Matches PBPS trainee_unique_id for your provider.",
      },
      {
        key: "trainee_name",
        label: "Trainee name",
        kind: "text",
        required: false,
        hint: "Optional helper column for review; import uses trainee_unique_id / trainee_id for matching.",
      },
      {
        key: "outcome_type",
        label: "Outcome type",
        kind: "text",
        required: true,
        hint: "Use completion (fixed if you only upload completion batches via this template).",
      },
      {
        key: "reported_value",
        label: "Completed",
        kind: "boolean",
        required: false,
        hint: "Y/N — whether the trainee completed training.",
      },
      {
        key: "status_date",
        label: "Status date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD. If empty, completion_date may be used.",
      },
      {
        key: "completion_date",
        label: "Completion date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD; stored as metadata and used as status date when status_date is empty.",
      },
      {
        key: "notes",
        label: "Notes",
        kind: "text",
        required: false,
        hint: "Optional notes for this completion row.",
      },
    ],
  },
  {
    reportType: "certification",
    title: "Certification",
    summary: "Certification outcomes for completers.",
    guidance: "Same as completion template pattern: outcome_type certification, reported_value Y/N.",
    columns: [
      {
        key: "trainee_unique_id",
        label: "Trainee unique ID",
        kind: "identifier",
        required: true,
        hint: "Roster ID.",
      },
      {
        key: "trainee_name",
        label: "Trainee name",
        kind: "text",
        required: false,
        hint: "Optional helper column for review; import uses trainee_unique_id / trainee_id for matching.",
      },
      {
        key: "outcome_type",
        label: "Outcome type",
        kind: "text",
        required: true,
        hint: "certification",
      },
      {
        key: "reported_value",
        label: "Certified",
        kind: "boolean",
        required: false,
        hint: "Y/N",
      },
      {
        key: "status_date",
        label: "Status date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD. If empty, certification_date may be used.",
      },
      {
        key: "certification_date",
        label: "Certification date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD; stored as metadata and used as status date when status_date is empty.",
      },
      {
        key: "notes",
        label: "Notes",
        kind: "text",
        required: false,
        hint: "Optional notes.",
      },
    ],
  },
  {
    reportType: "dropout",
    title: "Dropout",
    summary: "Mark trainees who dropped out.",
    guidance:
      "outcome_type dropout; reported_value Y/N. For reported_value=Y, dropout_reason is required. Allowed reasons: voluntary_withdrawal, dismissal, low_attendance_auto, health, economic, migration, other. Trainees whose attendance finished below 80% when the class ended are pre-filled Y and MUST be reported as Y: the upload is rejected if any of them is missing from the file or marked N, because attendance is the training provider's responsibility. If you believe the attendance itself was recorded incorrectly, fix the attendance first and then re-download this template.",
    columns: [
      {
        key: "trainee_unique_id",
        label: "Trainee unique ID",
        kind: "identifier",
        required: true,
        hint: "Roster ID.",
      },
      {
        key: "trainee_name",
        label: "Trainee name",
        kind: "text",
        required: false,
        hint: "Optional helper column for review; import uses trainee_unique_id / trainee_id for matching.",
      },
      {
        key: "outcome_type",
        label: "Outcome type",
        kind: "text",
        required: true,
        hint: "dropout",
      },
      {
        key: "reported_value",
        label: "Dropped out",
        kind: "boolean",
        required: false,
        hint: "Y/N",
      },
      {
        key: "status_date",
        label: "Status date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD. If empty, dropout_date may be used.",
      },
      {
        key: "dropout_date",
        label: "Dropout date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD; metadata and fallback for status date.",
      },
      {
        key: "dropout_reason",
        label: "Dropout reason",
        kind: "text",
        required: true,
        hint: "Required when reported_value=Y. Use one of: voluntary_withdrawal, dismissal, low_attendance_auto, health, economic, migration, other. For system-flagged low-attendance trainees use low_attendance_auto.",
      },
      {
        key: "dropout_notes",
        label: "Dropout notes",
        kind: "text",
        required: false,
        hint: "Additional detail.",
      },
    ],
  },
  {
    reportType: "job_retention_3m",
    title: "Job retention (3 months)",
    summary: "Follow-up: trainee still in employment at the 3‑month check-in among those who met the employment bundle.",
    guidance:
      "Use outcome_type job_retention_3m (legacy CSVs may say job_retention; import normalizes when this template is selected). reported_value Y/N; status_date is the check-in date.",
    columns: [
      {
        key: "trainee_unique_id",
        label: "Trainee unique ID",
        kind: "identifier",
        required: true,
        hint: "Roster ID.",
      },
      {
        key: "trainee_name",
        label: "Trainee name",
        kind: "text",
        required: false,
        hint: "Optional helper column for review; import uses trainee_unique_id / trainee_id for matching.",
      },
      {
        key: "outcome_type",
        label: "Outcome type",
        kind: "text",
        required: true,
        hint: "job_retention_3m",
      },
      {
        key: "reported_value",
        label: "Still employed",
        kind: "boolean",
        required: false,
        hint: "Y/N",
      },
      {
        key: "status_date",
        label: "Check-in date",
        kind: "date",
        required: false,
        hint: "YYYY-MM-DD",
      },
      {
        key: "notes",
        label: "Notes",
        kind: "text",
        required: false,
        hint: "Optional context for the retention check-in.",
      },
    ],
  },
];

/** Canonical order for TP roster outcome uploads (API + UI dropdowns). */
/** Grievance timeliness is tracked via the public feedback module, not TP CSV uploads. */
export const TP_OUTCOME_UPLOAD_ORDER = [
  "completion",
  "certification",
  "dropout",
  "employment_placement",
  "locality_compliant",
  "job_retention_3m",
] as const;

export const OUTCOME_TEMPLATE_DEFS: OutcomeTemplateDef[] = OUTCOME_TEMPLATE_DEFS_RAW.map((def) => ({
  ...def,
  columns: withExternalBeneficiaryColumn(def.columns),
}));

export type TpOutcomeUploadReportType = (typeof TP_OUTCOME_UPLOAD_ORDER)[number];

export function outcomeTemplatesForTpUpload(): OutcomeTemplateDef[] {
  return (TP_OUTCOME_UPLOAD_ORDER as readonly string[])
    .map((rt) => OUTCOME_TEMPLATE_DEFS.find((d) => d.reportType === rt))
    .filter((x): x is OutcomeTemplateDef => Boolean(x));
}

export function isTpOutcomeCsvReportType(reportType: string): reportType is TpOutcomeUploadReportType {
  return (TP_OUTCOME_UPLOAD_ORDER as readonly string[]).includes(reportType);
}

export function buildOutcomeTemplateCsvBody(
  reportType: string,
  prefilledRows?: Array<Record<string, string>>
): string | null {
  const def = OUTCOME_TEMPLATE_DEFS.find((d) => d.reportType === reportType);
  if (!def) return null;
  const header = def.columns.map((c) => c.key).join(",");
  if (prefilledRows && prefilledRows.length > 0) {
    const lines = prefilledRows.map((row) => def.columns.map((c) => row[c.key] ?? "").join(","));
    return `${header}\n${lines.join("\n")}\n`;
  }
  const exampleCells = def.columns.map((c) => {
    if (c.kind === "boolean") return "Y";
    if (c.kind === "date") return "2026-01-15";
    if (c.key === "outcome_type") return c.hint.split(/[,;]/)[0]?.trim() ?? reportType;
    return "EXAMPLE";
  });
  return `${header}\n${exampleCells.join(",")}\n`;
}
