import { pool } from "../config/db.js";
import { ApiError } from "./ApiError.js";

/**
 * Marks a form row as archived (superseded by a child version). Idempotent.
 * @param {import("mysql2/promise").PoolConnection | import("mysql2/promise").Pool} conn
 * @param {number} parentFormId
 */
export async function archiveOracFormParent(conn, parentFormId) {
  const pid = Number(parentFormId);
  if (!Number.isInteger(pid) || pid <= 0) {
    return;
  }
  await conn.query(
    "INSERT IGNORE INTO `orac_archive_form` (`form_id`, `archived_at`) VALUES (?, NOW())",
    [pid]
  );
}

/**
 * @param {import("mysql2/promise").PoolConnection | import("mysql2/promise").Pool} conn
 * @param {number} formId
 * @returns {Promise<boolean>}
 */
export async function isOracFormArchived(conn, formId) {
  const id = Number(formId);
  if (!Number.isInteger(id) || id <= 0) {
    return false;
  }
  const [rows] = await conn.query(
    "SELECT 1 AS ok FROM `orac_archive_form` WHERE `form_id` = ? LIMIT 1",
    [id]
  );
  return Boolean(rows?.length);
}

/** Pool helper for callers without a transaction connection. */
export async function assertOracFormNotArchived(formId, message) {
  const archived = await isOracFormArchived(pool, formId);
  if (archived) {
    throw new ApiError(400, message || "This form version is archived; use the current form for new work.");
  }
}
