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 archivePtwFormParent(conn, parentFormId) {
  const pid = Number(parentFormId);
  if (!Number.isInteger(pid) || pid <= 0) return;
  await conn.query(
    "INSERT IGNORE INTO `ptw_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 isPtwFormArchived(conn, formId) {
  const id = Number(formId);
  if (!Number.isInteger(id) || id <= 0) return false;
  const [rows] = await conn.query(
    "SELECT 1 AS ok FROM `ptw_archive_form` WHERE `form_id` = ? LIMIT 1",
    [id]
  );
  return Boolean(rows?.length);
}

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

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

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