import { json, pool, query, type Row } from "../../core/db/db.js";
import { toCsv, toXlsx, type Cell } from "../../core/files/table.js";
import { can, notFound, scope, type Ctx } from "../../core/http/route.js";
import { dmy } from "../../shared/dates.js";

/**
 * Trainees with "yes" for one report type, per provider (V1 port: GET reports/outcomes/:type.csv).
 * Except for the dropout export, dropouts are left out: the same rule the indicators use.
 */
export const EXPORTS = {
  completion: { file: "completers", label: "Completers", col: "completion_status", extra: [] },
  certification: { file: "certified", label: "Certified", col: "certification_status", extra: [] },
  dropout: { file: "dropouts", label: "Dropouts", col: "dropout_status", extra: [["Dropout reason", "reason"], ["Dropout notes", "dropout_notes"]] },
  employment_placement: {
    file: "employment-placement", label: "Employed (placement)", col: "placement_status",
    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", col: "locality_status", extra: [["Locality address", "locality_address"]] },
  job_retention_3m: { file: "job-retention-3m", label: "Retained 3 months", col: "retention_3m_status", extra: [] },
} as const satisfies Record<string, { file: string; label: string; col: string; extra: ReadonlyArray<readonly [string, string]> }>;

const PII = /^(Full name|Phone|Employer (contact|phone|email))$/;

export async function outcomeExport(c: Ctx, type: string, providerId: string | undefined, format: string) {
  if (!Object.hasOwn(EXPORTS, type)) notFound("Report type");
  const d = EXPORTS[type as keyof typeof EXPORTS], s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" });
  const rows = await query(pool, `SELECT p.name AS provider, l.name AS location, tr.title AS training, k.code AS class_code, k.effective_start AS cs, k.effective_end AS ce,
      t.trainee_code, t.external_beneficiary_id AS ext, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, t.sex, t.age_years, COALESCE(t.phone_e164,t.phone_raw) AS phone,
      t.roster_status, s.certification_status AS cert, x.event_date, x.legacy_status_date, x.reason_code, x.details_json, x.raw_json, r.source_filename AS file
    FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN training_classes k ON k.id=t.class_id
    JOIN training_sites ts ON ts.id=t.site_id LEFT JOIN locations l ON l.id=ts.location_id JOIN trainings tr ON tr.id=t.training_id
    LEFT JOIN outcome_report_lines x ON x.id=(SELECT ol.id FROM outcome_report_lines ol JOIN outcome_reports o ON o.id=ol.report_id
      WHERE ol.trainee_id=t.id AND o.report_type=? AND o.status='accepted' ORDER BY o.id DESC LIMIT 1)
    LEFT JOIN outcome_reports r ON r.id=x.report_id
    WHERE t.project_id=? AND t.roster_status IN ('active','reserve') AND ${s.sql} AND s.${d.col}='yes' ${type === "dropout" ? "" : "AND s.dropout_status<>'yes'"} ${providerId ? "AND t.provider_id=?" : ""}
    ORDER BY p.name, l.name, tr.title, k.code, t.trainee_code`, [type, c.pid, ...s.args, ...(providerId ? [providerId] : [])] as never[]);
  const pii = can(c, "trainee.view_pii");
  const header = ["Training provider", "Location", "Training", "Class", "Class start", "Class end", "Trainee ID", "External beneficiary ID", "Full name", "Sex", "Age", "Phone", "Roster role",
    `${d.label}: date (as reported)`, ...d.extra.map(([h]) => h), ...(type === "completion" ? ["Certified"] : []), "Report file"];
  const body = rows.map((r: Row) => {
    const m: Row = { ...json<Row>(r["raw_json"], {}), ...json<Row>(r["details_json"], {}), reason: r["reason_code"] ?? "" };
    const date = r["event_date"] ?? r["legacy_status_date"];
    const out: Cell[] = [r["provider"], r["location"], r["training"], r["class_code"], dmy(r["cs"] ?? ""), dmy(r["ce"] ?? ""), r["trainee_code"], r["ext"], r["name"], r["sex"], r["age_years"], r["phone"], r["roster_status"],
      date ? dmy(date) : "", ...d.extra.map(([, k]) => (m[k] == null ? "" : String(m[k]))), ...(type === "completion" ? [r["cert"] === "yes" ? "Yes" : r["cert"] === "no" ? "No" : ""] : []), r["file"]];
    return pii ? out : out.map((v, i) => (PII.test(header[i]!) ? "" : v));
  });
  const xlsx = format === "xlsx";
  return { name: `${d.file}.${xlsx ? "xlsx" : "csv"}`, xlsx, count: rows.length, body: xlsx ? await toXlsx(d.label, header, body, header) : toCsv(header, body) };
}
