import { dmy } from "../../shared/dates.js";
import { CHOICES, COLUMNS, PLACEMENT, SUPPORT } from "./placement.rules.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 OUTCOME_TEMPLATE_DEFS_RAW: OutcomeTemplateDef[] = [
  {
    reportType: PLACEMENT,
    title: "Employment placement",
    summary: "One row per certified trainee: the support received, and the job or business if there is one.",
    guidance:
      "reported_value is Yes when the trainee is in employment of any kind, otherwise No. The seven placement_support columns need Yes or No in every row. For No, leave every employment column empty. For Yes, fill employment_type and then: wage_employed needs job title, start date, income, contract type, employer name, contact person and the employer's email or phone. self_employed_business and self_employed_freelance need start date, income, legal form and business licence. other needs its explanation, start date and income. Dates: DD/MM/YYYY. Income: a number only, after deductions. Format the phone column as text.",
    columns: COLUMNS.map((key): TemplateColumn => ({
      key,
      label: key.replace(/_/g, " ").replace(/^./, (x) => x.toUpperCase()),
      kind: key === "trainee_unique_id" || key === "external_beneficiary_id" ? "identifier" : key.endsWith("_date") ? "date" : key === "reported_value" || key === "has_business_license" || (SUPPORT as readonly string[]).includes(key) ? "boolean" : "text",
      required: key === "trainee_unique_id" || key === "reported_value" || (SUPPORT as readonly string[]).includes(key),
      hint: key === "outcome_type" ? PLACEMENT : key === "job_title" ? "Job title or position. Required for wage_employed." : (CHOICES[key]?.join(" | ") ?? (key === "employer_phone" ? "Digits only, for example 0911234567." : key === "monthly_income_etb" ? "Number only, after deductions." : key.endsWith("_date") ? "DD/MM/YYYY" : (SUPPORT as readonly string[]).includes(key) ? "Yes/No, required in every 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: "DD/MM/YYYY",
      },
      {
        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: "DD/MM/YYYY. If empty, completion_date may be used.",
      },
      {
        key: "completion_date",
        label: "Completion date",
        kind: "date",
        required: false,
        hint: "DD/MM/YYYY; 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: "DD/MM/YYYY. If empty, certification_date may be used.",
      },
      {
        key: "certification_date",
        label: "Certification date",
        kind: "date",
        required: false,
        hint: "DD/MM/YYYY; 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: "DD/MM/YYYY. If empty, dropout_date may be used.",
      },
      {
        key: "dropout_date",
        label: "Dropout date",
        kind: "date",
        required: false,
        hint: "DD/MM/YYYY; 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: "DD/MM/YYYY",
      },
      {
        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);
}

/** Quoted where needed; a value that could run as a formula in Excel is written as text. */
const cell = (raw: string) => { const v = dmy(raw), x = /^[=+\-@]/.test(v) ? `'${v}` : v; return /[",\r\n]/.test(x) ? `"${x.replace(/"/g, '""')}"` : x; };

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) => cell(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 "15/01/2026";
    if (c.key === "outcome_type") return c.hint.split(/[,;]/)[0]?.trim() ?? reportType;
    return "EXAMPLE";
  });
  return `${header}\n${exampleCells.join(",")}\n`;
}
