import type { Connection } from "mysql2/promise";
import { query, type Db } from "../../src/core/db/db.js";

const norm = (s: string | null) => (s ?? "").toLowerCase().normalize("NFKD").replace(/\p{M}/gu, "").replace(/[^\p{L}\p{N}]+/gu, " ").trim();
export default async function enrich(raw: Connection): Promise<number> {
  const db = raw as unknown as Db, rows = await query(db, "SELECT id, first_name, father_name, grandfather_name FROM trainees");
  for (const t of rows) {
    const f = norm(t["first_name"]), g = norm(t["father_name"]), h = norm(t["grandfather_name"]);
    await db.query("UPDATE trainees SET name_norm_first=?, name_norm_father=?, name_norm_grandfather=?, name_key_fn_fa=?, updated_at=updated_at WHERE id=?",
      [f.slice(0, 60) || null, g.slice(0, 60) || null, h.slice(0, 60) || null, `${f} ${g}`.trim().slice(0, 120) || null, t["id"]]);
  }
  return rows.length;
}
