import { one, pool, query, type Db, type Row } from "../../core/db/db.js";
import { norm } from "../projects/index.js";
import type { EnumLookup } from "./trainee.rules.js";

export async function enumLookup(db: Db = pool): Promise<EnumLookup> {
  const map = new Map((await query(db, "SELECT domain, alias_norm, canonical FROM enum_aliases")).map((a) => [`${a["domain"]}:${a["alias_norm"]}`, a["canonical"] as string]));
  for (const r of await query(db, "SELECT code, name FROM regions")) map.set(`region:${norm(r["name"])}`, r["code"]);
  const extra: Record<string, Record<string, string>> = { disability: { hearing: "hearing", visual: "visual" }, education: { "bachelor degree": "bachelor", "above bachelor": "above_bachelor", bachelor: "bachelor", "above bachelor degree": "above_bachelor" }, employment: { "working full time": "full_time", "self employed": "self_employed", "self employed running own business": "self_employed", "self employed own business": "self_employed" } };
  for (const [d, e] of Object.entries(extra)) for (const [k, v] of Object.entries(e)) if (!map.has(`${d}:${k}`)) map.set(`${d}:${k}`, v);
  const canonical = new Set([...map.entries()].map(([k, v]) => `${k.split(":")[0]}:${v}`));
  return (domain, raw) => map.get(`${domain}:${norm(raw)}`) ?? (canonical.has(`${domain}:${raw.trim()}`) ? raw.trim() : undefined);
}
export const providerRules = async (db: Db, providerId: string): Promise<Row> => (await one(db, `SELECT p.*, pr.over_enrolment_pct AS pct, pr.code AS project_code, pr.registration_closed_at AS project_closed, COALESCE((SELECT k.target_trainees FROM provider_contracts k WHERE k.provider_id=p.id AND k.status IN ('active','amended') ORDER BY k.status='active' DESC, k.id DESC LIMIT 1),0) AS target,
  (SELECT COUNT(*) FROM trainees t WHERE t.provider_id=p.id AND t.roster_status IN ('active','reserve')) AS registered FROM providers p JOIN projects pr ON pr.id=p.project_id WHERE p.id=?`, [providerId]))!;
/** V1 rule: the contract target plus the project's over-enrolment allowance. */
export const maxRegistration = (target: number, pct: number) => Math.floor(target * (1 + pct / 100) + 1e-9);
