import type { Connection, ResultSetHeader, RowDataPacket } from "mysql2/promise";

// GONE: V1 renames decent job to *_retired when it merges the two itself (V1 migration 2026-12-03).
const OLD = "job_linkage_rate", GONE = ["decent_job_placement_rate", "decent_job_placement_rate_retired"], NEW = "employment_placement_rate";
/** The two indicators become one. Its formula, target and denominator are the ones both had. Numbers 15 to 19 move up by one. Safe to run again. */
export default async function merge(db: Connection): Promise<number> {
  const [has] = await db.query<RowDataPacket[]>("SELECT 1 FROM indicator_definitions WHERE code IN (?) LIMIT 1", [[OLD, ...GONE]]);
  if (!has.length) return 0;
  const run = async (sql: string, args: unknown[] = []) => (await db.query<ResultSetHeader>(sql, args))[0].affectedRows;
  const [a] = await db.query<RowDataPacket[]>("SELECT DISTINCT project_id AS p, denominator_metric AS d, default_target AS t FROM indicator_definitions WHERE code IN (?) AND status='active'", [[OLD, ...GONE]]);
  for (const p of new Set(a.map((x) => String(x["p"])))) if (a.filter((x) => String(x["p"]) === p).length > 1) throw new Error("Job linkage and decent job have different targets or denominators. Decide which one the merged indicator keeps.");
  let n = 0;
  for (const t of ["indicator_stages", "verification_plans", "indicator_targets", "kpi_snapshots", "indicator_definitions"]) n += await run(`DELETE FROM ${t} WHERE ${t === "verification_plans" ? "NOT EXISTS (SELECT 1 FROM verification_runs r WHERE r.plan_id=verification_plans.id) AND " : ""}indicator_code IN (?)`.replace("indicator_code IN (?)", t === "indicator_definitions" ? "code IN (?)" : "indicator_code IN (?)"), [GONE]);
  for (const t of ["indicator_stages", "verification_plans", "indicator_targets", "kpi_snapshots"]) n += await run(`UPDATE ${t} SET indicator_code=? WHERE indicator_code=?`, [NEW, OLD]);
  n += await run(`UPDATE indicator_definitions SET code=?, name='Employment placement rate', numerator_metric='trainees.placed', denominator_metric='trainees.completed_capped', operational_definition=?, data_sources=?, frequency=?, computation_text=? WHERE code IN (?)`, [NEW,
    "The proportion of trainees per Training Provider who are in employment of any kind (wage employment, self-employment in a business, freelance work or other) within 2 months of training completion. For each certified trainee the provider also reports the placement support given: outreach and referrals, job fairs, interview preparation, CV writing, direct placement, job matching and employer follow-up.",
    "Employment placement report of the Training Provider (one row per certified trainee), MIS trainee database, and the verification survey of sampled trainees.", "Once per class, within 60 days of training completion.", "Trainees reported as employed divided by the trainees who completed (up to the contract target), times 100.", [OLD, NEW]]);
  n += await run("UPDATE indicator_definitions SET numerator_metric=IF(numerator_metric IN ('trainees.job_linked','trainees.decent_job_final'),'trainees.placed',numerator_metric), denominator_metric=IF(denominator_metric IN ('trainees.job_linked','trainees.decent_job_final'),'trainees.placed',denominator_metric) WHERE 'trainees.job_linked' IN (numerator_metric,denominator_metric) OR 'trainees.decent_job_final' IN (numerator_metric,denominator_metric)");
  n += await run("UPDATE indicator_definitions SET protocol_no=protocol_no-1 WHERE protocol_no BETWEEN 16 AND 19");
  n += await run("UPDATE activity_definitions SET linked_indicator_code=? WHERE linked_indicator_code IN (?)", [NEW, [OLD, ...GONE]]);
  return n;
}
