import { audit } from "../../core/audit/audit.js";
import { execute, insert, one, pool, query, transaction, update, type Db, type Row, type SqlValue } from "../../core/db/db.js";
import { DomainError } from "../../core/http/errors.js";
import { can, classInScope, conflict, invalid, like, notFound, paging, scope, type Ctx } from "../../core/http/route.js";
import { cached } from "../../core/cache.js";
import { today } from "../../shared/dates.js";
import { showPhone } from "../../shared/phone.js";
import { allClasses, assertClassOpen, recomputeClass } from "../delivery/index.js";
import { refreshClassOutcomes } from "../outcomes/index.js";
import { queueKpis } from "../projects/index.js";
import { eligibility } from "./eligibility.rules.js";
import { enumLookup, maxRegistration, providerRules } from "./lookup.js";
import { checkTrainee, type Parsed } from "./trainee.rules.js";

/** Every column except the long JSON texts: sorting those made the list take seconds. */
const SELECT = `SELECT t.id, t.project_id, t.provider_id, t.training_id, t.site_id, t.class_id, t.trainee_code, t.external_beneficiary_id, t.roster_status, t.withdrawal_reason, t.withdrawn_at, t.replaces_trainee_id, t.attendance_eligible_from, t.first_name, t.father_name, t.grandfather_name, t.sex, t.sex_raw, t.age_years, t.dob_raw, t.date_of_birth, t.form_completion_date, t.form_date_confidence, t.phone_e164, t.phone_raw, t.phone_alt_e164, t.phone_alt_raw, t.email, t.kebele, t.woreda, t.sub_city, t.region_code, t.region_raw, t.emergency_contact_name, t.emergency_phone_e164, t.emergency_phone_raw, t.education_code, t.education_raw, t.previously_participated, t.prior_training_type, t.prior_completed, t.prior_year_completed, t.employment_code, t.employment_raw, t.income_sufficient, t.skill_usage_code, t.skill_usage_raw, t.plan_code, t.plan_raw, t.plan_other_text, t.is_pwd, t.disability_code, t.disability_raw, t.disability_other_text, t.is_idp, t.is_returnee, t.is_low_income, t.inclusion_none, t.inclusion_prefer_not_say, t.consent_accuracy, t.consent_followup, t.consent_contact_verify, t.consent_image_use, t.eligibility_status, t.name_norm_first, t.name_norm_father, t.name_norm_grandfather, t.name_key_fn_fa, t.name_phon_fn, t.name_phon_fa, t.legacy_training_type, t.legacy_training_location, t.legacy_location_id, t.legacy_duration_id, t.legacy_roster_role, t.import_batch_id, t.created_by, t.version, t.created_at, t.updated_at, s.att_present, s.att_absent, s.att_excused, s.att_sessions_to_date, s.att_sessions_total, s.att_rate_to_date, s.att_rate_final, s.att_max_reachable, s.system_dropout_risk, s.system_dropout_final, s.dropout_status, s.completion_status, s.completion_source, s.certification_status, s.placement_status, s.locality_status, s.retention_3m_status,
  p.code AS providerCode, p.name AS providerName, k.code AS classCode, k.name AS className, st.display_name AS siteName, tr.title AS trainingTitle, rg.name AS regionName 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 st ON st.id=t.site_id JOIN trainings tr ON tr.id=t.training_id LEFT JOIN regions rg ON rg.code=t.region_code`;
const opt = <T>(v: T | null | undefined) => v ?? undefined;
const bool = (v: unknown) => (v === null || v === undefined ? undefined : Boolean(v));
/** Personal details are returned only to people allowed to see them. */
export function view(c: Ctx, t: Row) {
  const pii = can(c, "trainee.view_pii");
  return { id: t["id"], code: t["trainee_code"], fullName: [t["first_name"], t["father_name"], t["grandfather_name"]].filter(Boolean).join(" "), firstName: t["first_name"], fatherName: t["father_name"] ?? "", grandfatherName: t["grandfather_name"] ?? "", sex: t["sex"], age: t["age_years"], phone: pii ? showPhone(t["phone_e164"]) || (t["phone_raw"] ?? "") : "", externalBeneficiaryId: opt(t["external_beneficiary_id"]),
    providerId: t["provider_id"], providerCode: t["providerCode"], providerName: t["providerName"], classId: t["class_id"], classCode: t["classCode"], className: t["className"], siteId: t["site_id"], siteName: t["siteName"], trainingId: t["training_id"], trainingTitle: t["trainingTitle"], rosterStatus: t["roster_status"], withdrawalReason: opt(t["withdrawal_reason"]), withdrawnAt: opt(t["withdrawn_at"]), eligibility: t["eligibility_status"], attendanceRate: opt(t["att_rate_to_date"]),
    dropout: t["dropout_status"], completion: t["completion_status"], completionSource: opt(t["completion_source"]), certification: t["certification_status"], placement: t["placement_status"], locality: t["locality_status"], retention3m: t["retention_3m_status"],
    region: t["regionName"] ?? t["region_raw"] ?? "", woreda: t["woreda"] ?? "", education: t["education_raw"] ?? t["education_code"] ?? "", employment: t["employment_raw"] ?? t["employment_code"] ?? "", registeredAt: t["created_at"], maxReachable: opt(t["att_max_reachable"]), systemDropoutRisk: !c.access.providerId && Boolean(t["system_dropout_risk"]), // withheld from provider staff, see dropoutMonitoring systemDropoutFinal: Boolean(t["system_dropout_final"]), present: t["att_present"], absent: t["att_absent"], excused: t["att_excused"], sessionsToDate: t["att_sessions_to_date"], sessionsTotal: t["att_sessions_total"], version: t["version"], formDateConfidence: t["form_date_confidence"],
    ...(pii ? { phoneAlt: showPhone(t["phone_alt_e164"]), email: opt(t["email"]), kebele: opt(t["kebele"]), subCity: opt(t["sub_city"]), emergencyName: opt(t["emergency_contact_name"]), emergencyPhone: showPhone(t["emergency_phone_e164"]), dateOfBirth: opt(t["date_of_birth"]), dobRecorded: opt(t["dob_raw"]), formDate: opt(t["form_completion_date"]), previouslyParticipated: bool(t["previously_participated"]), priorType: opt(t["prior_training_type"]), priorCompleted: bool(t["prior_completed"]), priorYear: opt(t["prior_year_completed"]), incomeSufficient: bool(t["income_sufficient"]), skillUsage: opt(t["skill_usage_raw"]), plan: t["plan_raw"] ?? "", planOther: opt(t["plan_other_text"]), disability: opt(t["disability_raw"]), disabilityOther: opt(t["disability_other_text"]),
      inclusion: [["is_pwd", "Person with disability"], ["is_idp", "Internally displaced person"], ["is_returnee", "Returnee"], ["is_low_income", "Low income"], ["inclusion_none", "None of the above"], ["inclusion_prefer_not_say", "Prefer not to say"]].filter(([k]) => t[k!]).map(([, l]) => l), consentAccuracy: bool(t["consent_accuracy"]), consentFollowup: bool(t["consent_followup"]), consentVerify: bool(t["consent_contact_verify"]), consentImage: bool(t["consent_image_use"]) } : {}) };
}
const S = (c: Ctx) => scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" });
export async function traineeRows(c: Ctx, where: string, args: SqlValue[], tail = "ORDER BY t.trainee_code"): Promise<ReturnType<typeof view>[]> {
  const s = S(c);
  // Narrow tables first, then the wide join for only the people found.
  const ids = (await query(pool, `SELECT t.id FROM trainees t ${`${where} ${tail}`.includes("s.") ? "JOIN trainee_status s ON s.trainee_id=t.id" : ""} WHERE t.project_id=? AND ${s.sql} AND ${where} ${tail}`, [c.pid, ...(s.args as SqlValue[]), ...args])).map((x) => x["id"] as string);
  const by = new Map((ids.length ? await query(pool, `${SELECT} WHERE t.id IN (?)`, [ids]) : []).map((t) => [t["id"] as string, t]));
  return ids.map((i) => view(c, by.get(i)!));
}
export async function getTrainee(c: Ctx, tid: string) {
  const t = (await traineeRows(c, "t.id=?", [tid]))[0] ?? notFound("Trainee");
  const [by, weeks] = await Promise.all([
    one(pool, "SELECT u.name FROM trainees t LEFT JOIN users u ON u.id=t.created_by WHERE t.id=?", [tid]),
    query(pool, "SELECT DATE_FORMAT(DATE_SUB(a.session_date, INTERVAL WEEKDAY(a.session_date) DAY),'%Y-%m-%d') AS week, SUM(m.status=1) AS present, SUM(m.status=2) AS absent, SUM(m.status=3) AS excused FROM attendance_marks m JOIN attendance_sessions a ON a.id=m.session_id WHERE m.trainee_id=? GROUP BY week ORDER BY week", [tid]),
  ]);
  return { ...t, registeredBy: opt(by?.["name"] as string | null), weeks: weeks.map((w) => ({ week: String(w["week"]), present: Number(w["present"]), absent: Number(w["absent"]), excused: Number(w["excused"]) })) };
}
export async function rawTrainee(c: Ctx, tid: string): Promise<Row> { const s = S(c); return (await one(pool, `SELECT t.* FROM trainees t WHERE t.id=? AND t.project_id=? AND ${s.sql}`, [tid, c.pid, ...s.args] as never[])) ?? notFound("Trainee"); }
const BANDS: Record<string, string> = { below80: "s.att_rate_to_date<80", "80to90": "s.att_rate_to_date>=80 AND s.att_rate_to_date<90", above90: "s.att_rate_to_date>=90", at_risk: "s.system_dropout_risk=1", none: "s.att_rate_to_date IS NULL" };
const SORT: Record<string, string> = { code: "t.trainee_code", name: "t.first_name", fullName: "t.first_name", attendanceRate: "s.att_rate_to_date", registeredAt: "t.created_at", age: "t.age_years" };
export async function listTrainees(c: Ctx) {
  const q = c.query, s = S(c), pg = paging(q), where = ["t.project_id=?", s.sql], args: unknown[] = [c.pid, ...s.args];
  for (const [k, col] of [["providerId", "t.provider_id"], ["trainingId", "t.training_id"], ["siteId", "t.site_id"], ["classId", "t.class_id"], ["rosterStatus", "t.roster_status"], ["sex", "t.sex"], ["eligibility", "t.eligibility_status"], ["dropout", "s.dropout_status"], ["completion", "s.completion_status"]] as const) if (q[k]) { where.push(`${col}=?`); args.push(q[k]); }
  if (q["band"] && BANDS[q["band"]] && !(q["band"] === "at_risk" && c.access.providerId)) where.push(`(${BANDS[q["band"]]})`);
  for (const word of (q["q"] ?? "").trim().split(/\s+/).filter(Boolean).slice(0, 5)) { const w = like(word), digits = word.replace(/\D/g, "").replace(/^(251|0)/, ""); where.push(`(t.first_name LIKE ? OR t.father_name LIKE ? OR t.grandfather_name LIKE ? OR t.trainee_code LIKE ? OR t.external_beneficiary_id LIKE ?${digits.length >= 5 && can(c, "trainee.view_pii") ? " OR t.phone_e164 LIKE ?" : ""})`); args.push(w, w, w, w, w, ...(digits.length >= 5 && can(c, "trainee.view_pii") ? [like(digits)] : [])); }
  const w = where.join(" AND "), join = /\bs\./.test(w) || /^s\./.test(SORT[(q["sort"] ?? "").split(":")[0]!] ?? "") ? "JOIN trainee_status s ON s.trainee_id=t.id" : "", [col, dir] = (q["sort"] ?? "code:asc").split(":");
  const total = (await one(pool, `SELECT COUNT(*) AS n FROM trainees t ${join} WHERE ${w}`, args as never[]))!["n"];
  // The page is found on the narrow tables first; only those few rows are joined with the rest.
  const ids = (await query(pool, `SELECT t.id FROM trainees t ${join} WHERE ${w} ORDER BY ${SORT[col!] ?? "t.trainee_code"} ${dir === "desc" ? "DESC" : "ASC"} LIMIT ? OFFSET ?`, [...args, pg.pageSize, pg.offset] as never[])).map((x) => x["id"] as string), by = new Map((ids.length ? await query(pool, `${SELECT} WHERE t.id IN (?)`, [ids]) : []).map((t) => [t["id"] as string, t]));
  return { items: ids.map((i) => view(c, by.get(i)!)), page: pg.page, pageSize: pg.pageSize, total };
}
export const summary = (c: Ctx) => cached(c, "trainee-summary", () => buildSummary(c), 10);
async function buildSummary(c: Ctx) {
  const s = S(c), r = (await one(pool, `SELECT SUM(t.roster_status='active') AS a, SUM(t.roster_status='reserve') AS r, SUM(t.roster_status IN ('active','reserve') AND t.sex='female') AS f, SUM(t.roster_status IN ('active','reserve') AND t.eligibility_status='eligible') AS e FROM trainees t WHERE t.project_id=? AND ${s.sql}`, [c.pid, ...s.args] as never[]))!;
  const ps = c.access.providerId ? [c.access.providerId] : (await query(pool, "SELECT id FROM providers WHERE project_id=?", [c.pid])).map((p) => String(p["id"]));
  let headroom = 0;
  for (const p of ps) { const x = await providerRules(pool, p); headroom += Math.max(0, maxRegistration(x["target"], x["pct"]) - x["registered"]); }
  const n = (r["a"] ?? 0) + (r["r"] ?? 0), pct = (x: number) => (n ? Math.round((x / n) * 1000) / 10 : 0);
  return { registrationOpen: (await allClasses(c)).some((k) => k.registrationOpen), active: r["a"] ?? 0, reserve: r["r"] ?? 0, femalePct: pct(r["f"] ?? 0), eligible: Number(r["e"] ?? 0), headroom };
}
/** V1 registration gate: project switch, provider switch, window dates, then capacity. */
export function assertOpen(p: Row, adding: number): void {
  const now = today();
  if (p["project_closed"]) throw new DomainError(409, "REGISTRATION_CLOSED", "Registration is closed for the project.");
  if (p["registration_closed_at"]) throw new DomainError(409, "REGISTRATION_CLOSED", "Registration is closed for this provider.");
  if (p["status"] !== "active") throw new DomainError(409, "PROVIDER_NOT_ACTIVE", "This provider is not active.");
  if (!(p["registration_late_until"] && now <= p["registration_late_until"])) if ((p["registration_open_from"] && now < p["registration_open_from"]) || (p["registration_open_until"] && now > p["registration_open_until"])) throw new DomainError(409, "REGISTRATION_CLOSED", "Registration is not open on this date.");
  if (!p["target"]) throw new DomainError(409, "NO_CONTRACT", "The provider has no contract target yet.");
  const max = maxRegistration(p["target"], p["pct"]);
  if (p["registered"] + adding > max) throw new DomainError(409, "CAPACITY_REACHED", `This would register ${p["registered"] + adding} trainees. The limit is ${max}.`);
}
export async function nextCodes(db: Db, providerId: string, n: number): Promise<string[]> {
  const p = (await one(db, "SELECT p.code, pr.code AS project FROM providers p JOIN projects pr ON pr.id=p.project_id WHERE p.id=?", [providerId]))!, token = (s: string) => s.toUpperCase().replace(/[^A-Z0-9]/g, "") || "X";
  await execute(db, "INSERT IGNORE INTO id_sequences (scope, next_value) VALUES (?,1)", [`trainee:${providerId}`]);
  const first = Number((await one(db, "SELECT next_value AS v FROM id_sequences WHERE scope=? FOR UPDATE", [`trainee:${providerId}`]))!["v"]);
  await execute(db, "UPDATE id_sequences SET next_value=next_value+? WHERE scope=?", [n, `trainee:${providerId}`]);
  return Array.from({ length: n }, (_, i) => `${token(p["project"])}-${token(p["code"])}-${String(first + i).padStart(6, "0")}`);
}
export const COLUMN_KEYS = { eligibility: (t: Parsed | Row) => eligibility({ age: (t["age_years"] as number) ?? null, education: (t["education_code"] as string) ?? null, employment: (t["employment_code"] as string) ?? null }) };
export async function insertTrainee(db: Db, c: Ctx, cls: Row, code: string, row: Parsed, extra: { batchId?: string; raw?: unknown } = {}): Promise<string> {
  const e = COLUMN_KEYS.eligibility(row), roster = (row["roster_status"] as string) ?? "active";
  const tid = await insert(db, "trainees", { ...(row as Record<string, SqlValue>), project_id: c.pid, provider_id: cls["provider_id"], training_id: cls["training_id"], site_id: cls["site_id"], class_id: cls["id"], trainee_code: code, roster_status: roster, eligibility_status: e.status, eligibility_reasons: JSON.stringify(e.reasons), import_batch_id: extra.batchId, created_by: c.user.id, raw_payload: extra.raw ? JSON.stringify(extra.raw) : undefined });
  const loc = await one(db, "SELECT location_id FROM training_sites WHERE id=?", [cls["site_id"]]);
  await insert(db, "trainee_status", { trainee_id: tid, project_id: c.pid, provider_id: cls["provider_id"], class_id: cls["id"], roster_status: roster, eligibility_status: e.status, sex: row["sex"] as string, location_id: loc?.["location_id"] ?? null });
  await insert(db, "trainee_class_history", { trainee_id: tid, class_id: cls["id"], from_date: today(), change_reason: "registered" });
  return tid;
}
export async function assertUniquePerson(db: Db, pid: string, row: Parsed, providerId: string, exceptId = "0"): Promise<void> {
  if (row["phone_e164"]) { const t = await one(db, "SELECT trainee_code FROM trainees WHERE project_id=? AND phone_e164=? AND id<>? AND roster_status IN ('active','reserve')", [pid, row["phone_e164"] as string, exceptId]); if (t) invalid("phone", `This phone number is already registered (${t["trainee_code"]}).`, "PHONE_DUPLICATE"); }
  if (row["external_beneficiary_id"]) { const t = await one(db, "SELECT trainee_code FROM trainees WHERE provider_id=? AND external_beneficiary_id=? AND id<>?", [providerId, row["external_beneficiary_id"] as string, exceptId]); if (t) invalid("externalBeneficiaryId", `This ID is already used (${t["trainee_code"]}).`, "EXTERNAL_ID_DUPLICATE"); }
}
/** Form field names to registration columns. */
const FORM: Record<string, string> = { externalBeneficiaryId: "external_beneficiary_id", formDate: "form_date", rosterStatus: "roster_status", firstName: "first_name", fatherName: "father_name", grandfatherName: "grandfather_name", sex: "sex", age: "age", dateOfBirth: "date_of_birth", phone: "phone", phoneAlt: "phone_alternative", email: "email", kebele: "kebele", woreda: "woreda", subCity: "sub_city", region: "region", emergencyName: "emergency_contact_name", emergencyPhone: "emergency_contact_phone", education: "education", previouslyParticipated: "previously_participated", priorType: "prior_training_type", priorCompleted: "prior_completed", priorYear: "prior_year_completed", employment: "employment", incomeSufficient: "income_sufficient", skillUsage: "skill_usage", plan: "plan", planOther: "plan_other", disability: "disability", disabilityOther: "disability_other", consentAccuracy: "consent_accuracy", consentFollowup: "consent_followup", consentVerify: "consent_contact_verify", consentImage: "consent_image_use" };
const BACK = Object.fromEntries(Object.entries(FORM).map(([a, b]) => [b, a]));
export function formToColumns(b: Row): Record<string, string> {
  const v: Record<string, string> = {};
  for (const [k, col] of Object.entries(FORM)) if (b[k] !== undefined && b[k] !== null) v[col] = String(b[k]);
  if (Array.isArray(b["inclusion"])) for (const [label, col] of [[/disab/, "is_pwd"], [/displac|\bidp\b/, "is_idp"], [/return/, "is_returnee"], [/income/, "is_low_income"], [/none/, "inclusion_none"], [/prefer/, "inclusion_prefer_not_to_say"]] as const) v[col] = String((b["inclusion"] as string[]).some((x) => label.test(x.toLowerCase())));
  return v;
}
async function checkForm(b: Row, p: Row, partial: boolean): Promise<Parsed> {
  const { row, issues } = checkTrainee({ ...formToColumns(b), ...(partial ? {} : { class_code: "-" }) }, { lookup: await enumLookup(), requireExternalId: Boolean(p["requires_external_id"]), externalIdLabel: p["external_id_label"], partial });
  const errors = issues.filter((i) => i.severity === "error");
  if (errors.length) throw new DomainError(422, "VALIDATION", `Fix ${errors.length} fields to save.`, errors.map((i) => ({ path: BACK[i.field] ?? i.field, code: i.code, message: i.message })));
  return row;
}
export async function createTrainee(c: Ctx, b: Row) {
  const cls = await classInScope(c, String(b["classId"]));
  await assertClassOpen(pool, cls["id"]);
  const row = await checkForm(b, await providerRules(pool, cls["provider_id"]), false);
  const tid = await transaction(async (tx) => {
    await one(tx, "SELECT id FROM providers WHERE id=? FOR UPDATE", [cls["provider_id"]]);
    assertOpen(await providerRules(tx, cls["provider_id"]), 1);
    await assertUniquePerson(tx, c.pid, row, cls["provider_id"]);
    const id = await insertTrainee(tx, c, cls, (await nextCodes(tx, cls["provider_id"], 1))[0]!, row, { raw: b });
    await afterRosterChange(tx, c, cls["id"]);
    await audit(tx, c, { module: "registration", action: "trainee_registered", entityType: "trainee", entityId: id, providerId: cls["provider_id"], summary: `Registered a trainee in ${cls["code"]}`, after: row });
    return id;
  });
  return getTrainee(c, tid);
}
export async function afterRosterChange(db: Db, c: Ctx, classId: string): Promise<void> { await recomputeClass(db, classId); await refreshClassOutcomes(db, classId); await queueKpis(db, c.pid); }
/** After the window nothing changes, except that an administrator may correct how to contact the person (V1's phone correction). */
const CONTACT = new Set(["phone", "phoneAlt", "email", "version"]);
export async function updateTrainee(c: Ctx, tid: string, b: Row) {
  const t = await rawTrainee(c, tid), contactOnly = Object.keys(b).every((k) => CONTACT.has(k));
  if (!(contactOnly && can(c, "project.manage"))) await assertClassOpen(pool, t["class_id"]);
  await applyTrainee(pool, c, t, await checkForm(b, await providerRules(pool, t["provider_id"]), true), b["version"]);
  return getTrainee(c, tid);
}
export async function applyTrainee(db: Db, c: Ctx, t: Row, row: Parsed, version?: number): Promise<void> {
  await assertUniquePerson(db, c.pid, row, t["provider_id"], t["id"]);
  const e = COLUMN_KEYS.eligibility({ ...t, ...row });
  const work = async (tx: Db) => {
    if (version !== undefined && Number((await one(tx, "SELECT version AS v FROM trainees WHERE id=? FOR UPDATE", [t["id"]]))!["v"]) !== version) conflict("CHANGED_BY_OTHERS", "Someone else changed this trainee. Reload and try again.");
    await update(tx, "trainees", t["id"], { ...(row as Record<string, SqlValue>), eligibility_status: e.status, eligibility_reasons: JSON.stringify(e.reasons), version: t["version"] + 1 });
    await execute(tx, "UPDATE trainee_status SET eligibility_status=?, sex=COALESCE(?,sex), roster_status=COALESCE(?,roster_status) WHERE trainee_id=?", [e.status, (row["sex"] as string) ?? null, (row["roster_status"] as string) ?? null, t["id"]]);
    await afterRosterChange(tx, c, t["class_id"]);
    await audit(tx, c, { module: "registration", action: "trainee_updated", entityType: "trainee", entityId: t["id"], providerId: t["provider_id"], summary: `Changed ${t["trainee_code"]}`, before: Object.fromEntries(Object.keys(row).map((k) => [k, t[k]])), after: row });
  };
  if (db === pool) await transaction(work); else await work(db);
}
export async function timeline(c: Ctx, tid: string) {
  const t = await rawTrainee(c, tid);
  const events = await query(pool, "SELECT e.occurred_at AS at, COALESCE(u.name,'System') AS actor, e.summary AS title FROM audit_events e LEFT JOIN users u ON u.id=e.actor_user_id WHERE e.project_id=? AND e.entity_type='trainee' AND e.entity_id=? ORDER BY e.id DESC LIMIT 100", [c.pid, tid]);
  const lines = await query(pool, "SELECT COALESCE(r.submitted_at,r.created_at) AS at, COALESCE(u.name,'') AS actor, CONCAT(REPLACE(r.report_type,'_',' '), IF(r.stage_key='','',CONCAT(' ',r.stage_key)), ': ', l.value) AS title, CONCAT('Version ', r.version_no, ', ', r.status, IF(l.event_date IS NULL,'',CONCAT(', ',l.event_date))) AS detail FROM outcome_report_lines l JOIN outcome_reports r ON r.id=l.report_id LEFT JOIN users u ON u.id=r.submitted_by WHERE l.trainee_id=?", [tid]);
  return [...events, ...lines, { at: t["created_at"], actor: "", title: "Registered" }].sort((a, b) => (String((a as Row)["at"]) < String((b as Row)["at"]) ? 1 : -1));
}
export async function phoneCheck(c: Ctx, phone: string) {
  const { parsePhone } = await import("../../shared/phone.js"), p = parsePhone(phone);
  if (!p.ok) return { valid: false, message: p.message, exists: false };
  return { valid: true, exists: Boolean(await one(pool, "SELECT 1 AS x FROM trainees WHERE project_id=? AND phone_e164=? AND roster_status IN ('active','reserve')", [c.pid, p.e164])) };
}
