import { isDate, parseFormDate, today } from "../../shared/dates.js";
import { parsePhone } from "../../shared/phone.js";

/** The one name of this report, in the file, the database and the indicator. */
export const PLACEMENT = "employment_placement";
export const SUPPORT = ["placement_support_outreach_referrals", "placement_support_job_fair", "placement_support_interview_prep", "placement_support_cv_writing", "placement_support_direct_placement", "placement_support_job_matching", "placement_support_employer_followup"] as const;
const EMPLOYER = ["employer_name", "employer_contact_person", "employer_contact_position", "employer_email", "employer_phone"] as const;
export const JOB = ["employment_type", "employment_type_other_text", "job_title", "employment_start_date", "monthly_income_etb", "contract_type", "contract_type_other_text", ...EMPLOYER, "legal_form", "legal_form_other_text", "has_business_license"] as const;
/** The 29 columns, in the order of the file. */
export const COLUMNS = ["external_beneficiary_id", "trainee_unique_id", "trainee_name", "outcome_type", "reported_value", "status_date", ...SUPPORT, ...JOB, "notes"] as const;
export const CHOICES: Record<string, readonly string[]> = {
  employment_type: ["wage_employed", "self_employed_business", "self_employed_freelance", "other"],
  contract_type: ["full_time_permanent", "contract_under_12_months", "contract_12_months_or_more", "other"],
  legal_form: ["sole_proprietorship", "partnership", "plc", "no_legal_form", "other"],
};
/** Which job columns each kind of employment needs. Everything else must stay empty. */
const NEEDS: Record<string, readonly string[]> = {
  wage_employed: ["job_title", "employment_start_date", "monthly_income_etb", "contract_type", "employer_name", "employer_contact_person"],
  self_employed_business: ["employment_start_date", "monthly_income_etb", "legal_form", "has_business_license"],
  self_employed_freelance: ["employment_start_date", "monthly_income_etb", "legal_form", "has_business_license"],
  other: ["employment_type_other_text", "employment_start_date", "monthly_income_etb"],
};
const MAY: Record<string, readonly string[]> = { wage_employed: ["contract_type_other_text", "employer_contact_position", "employer_email", "employer_phone"], self_employed_business: ["job_title", "legal_form_other_text"], self_employed_freelance: ["job_title", "legal_form_other_text"], other: ["job_title"] };
export const yesNo = (v: string): "yes" | "no" | undefined => (/^(yes|y|true|1)$/i.test(v.trim()) ? "yes" : /^(no|n|false|0)$/i.test(v.trim()) ? "no" : undefined);
export interface Problem { field: string; message: string }
/** One trainee's answers. Returns what is wrong, and the values in the form they are stored in. */
export function checkPlacement(value: "yes" | "no", raw: Record<string, string | undefined>, now = today()): { problems: Problem[]; clean: Record<string, string> } {
  const d: Record<string, string> = {}, problems: Problem[] = [], bad = (field: string, message: string) => problems.push({ field, message: `${field}: ${message}` });
  for (const k of [...SUPPORT, ...JOB, "notes"]) { const v = (raw[k] ?? "").trim(); if (v.length > 500) bad(k, "is too long."); else if (v) d[k] = v; }
  const choice = (k: string, v: string) => { const x = v.toLowerCase().replace(/[\s-]+/g, "_"); if (CHOICES[k]!.includes(x)) d[k] = x; else bad(k, `"${v}" is not possible. Use ${CHOICES[k]!.join(", ")}.`); };
  const flag = (k: string, v: string) => { const x = yesNo(v); if (x) d[k] = x; else bad(k, "use Yes or No."); };
  for (const k of SUPPORT) if (d[k]) flag(k, d[k]!); else bad(k, "Yes or No is required.");
  if (value === "no") { for (const k of JOB) if (d[k]) bad(k, "must be empty because the trainee is not employed."); return { problems, clean: d }; }
  if (!d["employment_type"]) { bad("employment_type", `is required. Use ${CHOICES["employment_type"]!.join(", ")}.`); return { problems, clean: d }; }
  choice("employment_type", d["employment_type"]);
  const type = d["employment_type"]!, needs = NEEDS[type];
  if (!needs) return { problems, clean: d };
  for (const k of needs) if (!d[k]) bad(k, `is required for ${type}.`);
  for (const k of JOB) if (k !== "employment_type" && d[k] && !needs.includes(k) && !MAY[type]!.includes(k)) bad(k, `must be empty for ${type}.`);
  if (type === "wage_employed" && !d["employer_email"] && !d["employer_phone"]) bad("employer_phone", "give the employer's email or phone.");
  for (const k of ["contract_type", "legal_form"]) {
    if (!d[k] || (!needs.includes(k) && !MAY[type]!.includes(k))) continue;
    choice(k, d[k]!);
    const text = `${k}_other_text`;
    if (d[k] === "other" && !d[text]) bad(text, `is required when ${k} is other.`);
    if (d[k] !== "other" && d[text]) bad(text, `must be empty unless ${k} is other.`);
  }
  if (d["has_business_license"] && needs.includes("has_business_license")) flag("has_business_license", d["has_business_license"]);
  if (d["employment_start_date"]) {
    const v = d["employment_start_date"], x = isDate(v) ? v : parseFormDate(v);
    if (!x) bad("employment_start_date", `"${v}" is not a clear date. Use DD/MM/YYYY (day first).`); else if (x > now) bad("employment_start_date", `${x} is in the future.`); else if (x < "1990-01-01") bad("employment_start_date", `${x} is too long ago.`); else d["employment_start_date"] = x;
  }
  if (d["monthly_income_etb"] && (!/^\d{1,9}(\.\d{1,2})?$/.test(d["monthly_income_etb"]) || Number(d["monthly_income_etb"]) <= 0)) bad("monthly_income_etb", `"${d["monthly_income_etb"]}" is not possible. Write only a number above 0, without commas or text.`);
  if (d["employer_email"] && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(d["employer_email"])) bad("employer_email", "is not an email address.");
  if (d["employer_phone"] && type === "wage_employed") { const p = parsePhone(d["employer_phone"]); if (p.ok) d["employer_phone"] = p.e164; else bad("employer_phone", p.message); }
  return { problems, clean: d };
}
