/**
 * One-off: adds orac_assessments.form_id (see migrations/001_add_orac_assessments_form_id.sql).
 * Run from repo: node scripts/apply-form-id-migration.js
 */
import dotenv from "dotenv";
import mysql from "mysql2/promise";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
dotenv.config({ path: path.join(__dirname, "..", ".env") });

const {
  DB_HOST = "127.0.0.1",
  DB_PORT = "3306",
  DB_USER = "root",
  DB_PASSWORD = "12345"
} = process.env;

const sqlPath = path.join(__dirname, "..", "migrations", "001_add_orac_assessments_form_id.sql");
const sql = fs.readFileSync(sqlPath, "utf8");

const conn = await mysql.createConnection({
  host: DB_HOST,
  port: Number(DB_PORT),
  user: DB_USER,
  password: DB_PASSWORD,
  database: "hse",
  multipleStatements: true
});

try {
  await conn.query(sql);
  console.log("Migration applied: orac_assessments.form_id added.");
} catch (e) {
  if (e.code === "ER_DUP_FIELDNAME" || String(e.message).includes("Duplicate column name")) {
    console.log("Column form_id already exists — nothing to do.");
  } else {
    console.error(e.message);
    process.exitCode = 1;
  }
} finally {
  await conn.end();
}
