import type { Connection, RowDataPacket } from "mysql2/promise";
import type { Check } from "./reconcile.js";

/** Copies EVERY V1 table verbatim into pbps_legacy and proves it row for row with CHECKSUM TABLE. */
export async function archive(db: Connection): Promise<Check[]> {
  const [tables] = await db.query<RowDataPacket[]>("SELECT table_name AS t FROM information_schema.tables WHERE table_schema='pbps_mis' AND table_type='BASE TABLE' ORDER BY 1");
  const checks: Check[] = [];
  await db.query("SET SESSION sql_mode=''"); // verbatim: V1 rows must not be judged by the stricter V2 rules
  const sum = async (schema: string, t: string) => {
    const [r] = await db.query<RowDataPacket[]>(`CHECKSUM TABLE ${schema}.\`${t}\` EXTENDED`);
    const [c] = await db.query<RowDataPacket[]>(`SELECT COUNT(*) AS n FROM ${schema}.\`${t}\``);
    return `${c[0]!["n"]} rows, checksum ${r[0]!["Checksum"]}`;
  };
  for (const { t } of tables as unknown as { t: string }[]) {
    await db.query(`DROP TABLE IF EXISTS pbps_legacy.\`${t}\``);
    await db.query(`CREATE TABLE pbps_legacy.\`${t}\` LIKE pbps_mis.\`${t}\``);
    await db.query(`INSERT INTO pbps_legacy.\`${t}\` SELECT * FROM pbps_mis.\`${t}\``);
    const [v1, v2] = [await sum("pbps_mis", t), await sum("pbps_legacy", t)];
    checks.push({ name: `archive ${t}`, v1, v2, ok: v1 === v2 && !v1.includes("null") });
  }
  checks.push({ name: "archived table count is not zero", v1: "> 0", v2: String(tables.length), ok: tables.length > 0 });
  return checks;
}
