/**
 * Historical typo: table was created as sat_form_quesiton_map ("quesiton").
 * SAT_backend code uses sat_form_question_map — INSERTs fail with ER_NO_SUCH_TABLE.
 *
 * Renames to the correct name if needed. Idempotent.
 *
 * Usage: npm run migrate:sat-form-question-map-name
 */
const pool = require("../src/config/db");

async function tableExists(name) {
  const [rows] = await pool.query(
    `SELECT COUNT(*) AS c FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`,
    [name]
  );
  return rows[0].c > 0;
}

async function main() {
  const correct = "sat_form_question_map";
  const typo = "sat_form_quesiton_map";
  try {
    if (await tableExists(correct)) {
      console.log(`[skip] ${correct} already exists`);
      return;
    }
    if (await tableExists(typo)) {
      await pool.query(`RENAME TABLE \`${typo}\` TO \`${correct}\``);
      console.log(`[ok]   Renamed ${typo} -> ${correct}`);
      console.log("Done.");
      return;
    }
    console.error(
      `[error] Neither ${correct} nor ${typo} exists. Create ${correct} manually or restore from backup.`
    );
    process.exitCode = 1;
  } catch (e) {
    console.error(e);
    process.exitCode = 1;
  } finally {
    await pool.end();
  }
}

main();
