import { createHash } from "node:crypto";
import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve, sep } from "node:path";
import type { Connection, RowDataPacket } from "mysql2/promise";

/** Copies V1 evidence files into V2 storage and records their SHA-256. A missing file is recorded and fails reconciliation, so a cutover cannot pass without it. */
export default async function copyFiles(db: Connection): Promise<number> {
  const from = process.env["V1_UPLOADS_DIR"];
  if (!from) throw new Error("V1_UPLOADS_DIR is not set");
  const source = resolve(from), target = resolve(process.env["STORAGE_DIR"] ?? "./storage");
  // Everything on disk is kept, including uploads that no V1 row points to.
  cpSync(source, join(target, "legacy"), { recursive: true });
  const [rows] = await db.query<RowDataPacket[]>("SELECT id, storage_key, legacy_path, size_bytes FROM files WHERE legacy_path IS NOT NULL");
  for (const row of rows) {
    const relativePath = String(row["legacy_path"]).replace(/\\/g, "/").replace(/^.*?uploads\//, "");
    const src = resolve(source, relativePath), dst = resolve(target, String(row["storage_key"]));
    if (!src.startsWith(source + sep) || !dst.startsWith(target + sep)) throw new Error(`File ${row["id"]}: path escapes its folder`);
    if (!existsSync(src)) {
      await db.query("INSERT INTO migration_issues (entity, entity_id, field, issue_code, raw_value, severity) VALUES ('file', ?, 'storage_key', 'FILE_MISSING_AT_SOURCE', ?, 'error') ON DUPLICATE KEY UPDATE raw_value = VALUES(raw_value)", [row["id"], relativePath]);
      continue;
    }
    mkdirSync(dirname(dst), { recursive: true });
    copyFileSync(src, dst);
    const bytes = readFileSync(dst);
    if (row["size_bytes"] !== null && bytes.length !== Number(row["size_bytes"])) throw new Error(`File ${row["id"]}: size differs from V1`);
    await db.query("UPDATE files SET sha256 = ? WHERE id = ?", [createHash("sha256").update(bytes).digest("hex"), row["id"]]);
  }
  return rows.length;
}
