import { Prisma } from "@prisma/client";
import { prisma } from "../prisma.js";

/**
 * Trainees a training provider reported "Yes" for one report type (their latest line of that type),
 * on the active/reserve roster. Except for the dropout export, trainees whose latest dropout line is
 * Yes are left out: the same rule the indicator counts use.
 */
export const OUTCOME_EXPORTS = {
  completion: { file: "completers", label: "Completers", dateKey: "completion_date", extra: [] },
  certification: { file: "certified", label: "Certified", dateKey: "certification_date", extra: [] },
  dropout: {
    file: "dropouts", label: "Dropouts", dateKey: "dropout_date",
    extra: [["Dropout reason", "dropout_reason"], ["Dropout notes", "dropout_notes"]],
  },
  employment_placement: {
    file: "employment-placement", label: "Employed (placement)", dateKey: "employment_start_date",
    extra: [
      ["Employment type", "employment_type"], ["Job title", "job_title"], ["Monthly income (ETB)", "monthly_income_etb"],
      ["Contract type", "contract_type"], ["Employer", "employer_name"], ["Employer contact", "employer_contact_person"],
      ["Employer phone", "employer_phone"], ["Employer email", "employer_email"], ["Legal form", "legal_form"],
      ["Business licence", "has_business_license"],
    ],
  },
  locality_compliant: { file: "locality-compliant", label: "Locality compliant", dateKey: "status_date", extra: [["Locality address", "locality_address"]] },
  job_retention_3m: { file: "job-retention-3m", label: "Retained 3 months", dateKey: "status_date", extra: [] },
} as const satisfies Record<string, { file: string; label: string; dateKey: string; extra: ReadonlyArray<readonly [string, string]> }>;

export type OutcomeExportType = keyof typeof OUTCOME_EXPORTS;
export const isOutcomeExportType = (v: string): v is OutcomeExportType => Object.hasOwn(OUTCOME_EXPORTS, v);

type Row = {
  provider: string;
  location: string | null;
  training: string | null;
  cohort: string | null;
  class_name: string | null;
  class_start: Date | null;
  class_end: Date | null;
  trainee_code: string | null;
  external_id: string | null;
  first_name: string;
  father_name: string | null;
  grandfather_name: string | null;
  sex: string | null;
  age_years: number | null;
  phone: string | null;
  roster_role: string;
  outcome_meta: unknown;
  outcome_status_date: Date | null;
  report_file: string | null;
  certified: number | null;
};

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

function cell(v: unknown): string {
  const s = v == null ? "" : String(v);
  return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}

function metaOf(v: unknown): Record<string, unknown> {
  let m = v;
  if (typeof m === "string") {
    try { m = JSON.parse(m); } catch { m = null; }
  }
  return m && typeof m === "object" && !Array.isArray(m) ? (m as Record<string, unknown>) : {};
}

export async function outcomeExportCsv(projectId: bigint, type: OutcomeExportType, providerId: bigint | null) {
  const def = OUTCOME_EXPORTS[type];
  const notDropout = type === "dropout"
    ? Prisma.empty
    : Prisma.sql`AND COALESCE((SELECT o.reported_value FROM trainee_outcomes o
                   WHERE o.trainee_id = t.id AND o.outcome_type = 'dropout' ORDER BY o.id DESC LIMIT 1), 0) <> 1`;
  const rows = await prisma.$queryRaw<Row[]>`
    SELECT tp.name AS provider, COALESCE(lc.name, lt.name) AS location, tr.title AS training,
           c.name AS cohort, b.name AS class_name, b.start_date AS class_start, b.end_date AS class_end,
           t.trainee_unique_id AS trainee_code, t.external_beneficiary_id AS external_id,
           t.first_name, t.father_name, t.grandfather_name, t.sex, t.age_years, t.phone_primary AS phone,
           t.roster_role, x.meta AS outcome_meta, x.status_date AS outcome_status_date, rb.source_filename AS report_file,
           (SELECT o.reported_value FROM trainee_outcomes o
             WHERE o.trainee_id = t.id AND o.outcome_type = 'certification' ORDER BY o.id DESC LIMIT 1) AS certified
    FROM trainees t
    JOIN training_providers tp ON tp.id = t.training_provider_id
    JOIN trainee_outcomes x ON x.id = (
      SELECT MAX(o.id) FROM trainee_outcomes o WHERE o.trainee_id = t.id AND o.outcome_type = ${type})
    LEFT JOIN outcome_report_batches rb ON rb.id = x.report_batch_id
    LEFT JOIN training_cohorts c ON c.id = t.cohort_id
    LEFT JOIN locations lc ON lc.id = c.location_id
    LEFT JOIN locations lt ON lt.id = t.location_id
    LEFT JOIN trainings tr ON tr.id = t.training_id
    LEFT JOIN training_batches b ON b.id = t.batch_id
    WHERE t.project_id = ${projectId}
      ${providerId ? Prisma.sql`AND t.training_provider_id = ${providerId}` : Prisma.empty}
      AND t.roster_role IN ('active', 'reserve')
      AND x.reported_value = 1
      ${notDropout}
    ORDER BY tp.name, location, tr.title, b.name, t.trainee_unique_id`;

  const headers = [
    "Training provider", "Location", "Training", "Cohort", "Class", "Class start", "Class end",
    "Trainee ID", "External beneficiary ID", "Full name", "Sex", "Age", "Phone", "Roster role",
    `${def.label}: date (as reported)`, ...def.extra.map(([h]) => h),
    ...(type === "completion" ? ["Certified"] : []), "Report file",
  ];
  const lines = rows.map((r) => {
    const m = metaOf(r.outcome_meta);
    const date = r.outcome_status_date ? dmy(r.outcome_status_date) : String(m[def.dateKey] ?? "");
    return [
      r.provider, r.location, r.training, r.cohort, r.class_name, dmy(r.class_start), dmy(r.class_end),
      r.trainee_code, r.external_id, [r.first_name, r.father_name, r.grandfather_name].filter(Boolean).join(" "),
      r.sex, r.age_years, r.phone, r.roster_role, date, ...def.extra.map(([, k]) => m[k] ?? ""),
      ...(type === "completion" ? [r.certified == null ? "" : Number(r.certified) === 1 ? "Yes" : "No"] : []),
      r.report_file,
    ].map(cell).join(",");
  });
  // BOM so Excel opens names in UTF-8.
  return { csv: `﻿${[headers.map(cell).join(","), ...lines].join("\r\n")}\r\n`, count: rows.length, file: def.file };
}
