/**
 * Idempotent: add allows_media + ai_fill to sat_questions if missing.
 * Fixes: "Unknown column 'allows_media' in 'field list'"
 *
 * Usage (from SAT_backend folder):
 *   node scripts/apply-sat-questions-columns.js
 */
const path = require("path");
require("dotenv").config({ path: path.join(__dirname, "..", ".env") });

const pool = require("../src/config/db");

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

async function addColumnIfMissing(tableName, columnName, ddl) {
  if (await columnExists(tableName, columnName)) {
    console.log(`[skip] ${tableName}.${columnName} already exists`);
    return;
  }
  await pool.query(ddl);
  console.log(`[ok]   ${tableName}.${columnName} added`);
}

async function main() {
  try {
    await addColumnIfMissing(
      "sat_questions",
      "allows_media",
      "ALTER TABLE sat_questions ADD COLUMN allows_media TINYINT(1) NOT NULL DEFAULT 0"
    );
    await addColumnIfMissing(
      "sat_questions",
      "ai_fill",
      "ALTER TABLE sat_questions ADD COLUMN ai_fill TINYINT(1) NOT NULL DEFAULT 0"
    );
    console.log("Done.");
  } catch (e) {
    console.error(e);
    process.exitCode = 1;
  } finally {
    await pool.end();
  }
}

main();
