import type { Prisma } from "@prisma/client";

const ELIGIBLE_EDUCATION_CANONICAL = [
  "secondary (grades 9–12)",
  "high school dropout",
  "tvet certificate level i–iv",
  "diploma",
  "bachelor's degree",
  "above bachelor's",
] as const;

const ELIGIBLE_EMPLOYMENT_CANONICAL = [
  "not currently working",
  "working occasionally",
  "working fewer hours than desired",
] as const;

function compact(v: string): string {
  return v
    .trim()
    .toLowerCase()
    .replace(/[’]/g, "'")
    .replace(/\s+/g, " ");
}

export function normalizeHighestEducation(value?: string | null): string | null {
  if (!value) return null;
  const v = compact(value);
  if (
    v.includes("secondary") ||
    v.includes("grade 12") ||
    v.includes("g12") ||
    v.includes("12th") ||
    v.includes("grades 9-12") ||
    v.includes("grades 9–12")
  ) {
    return "secondary (grades 9–12)";
  }
  if (v.includes("dropout") || v.includes("high school dropout") || v.includes("12 dropout")) {
    return "high school dropout";
  }
  if (
    v.includes("tvet") ||
    v.includes("certificate level") ||
    v.includes("level i") ||
    v.includes("level ii") ||
    v.includes("level iii") ||
    v.includes("level iv")
  ) {
    return "tvet certificate level i–iv";
  }
  if (v.includes("diploma")) return "diploma";
  if (v.includes("above bachelor")) return "above bachelor's";
  if (v.includes("bachelor")) return "bachelor's degree";
  return value.trim();
}

export function normalizeEmploymentStatus(value?: string | null): string | null {
  if (!value) return null;
  const v = compact(value);
  if (v.includes("not currently working") || v.includes("unemploy")) {
    return "not currently working";
  }
  if (v.includes("working occasionally")) {
    return "working occasionally";
  }
  if (v.includes("fewer hours than desired") || v.includes("underemploy")) {
    return "working fewer hours than desired";
  }
  return value.trim();
}

/** Protocol §4: age 18–29, qualifying education, unemployed/underemployed at enrollment. */
export function eligibilityProtocolWhere(): Prisma.TraineeWhereInput {
  return {
    ageYears: { gte: 18, lte: 29 },
    highestEducation: { in: [...ELIGIBLE_EDUCATION_CANONICAL] },
    employmentStatus: { in: [...ELIGIBLE_EMPLOYMENT_CANONICAL] },
  };
}
