import { ApiError } from "./ApiError.js";

export async function getSectionQuestionIds(conn, sectionId) {
  const [rows] = await conn.query(
    `SELECT m.question_id
     FROM ptw_section_question_map m
     INNER JOIN ptw_questions q ON q.question_id = m.question_id
     WHERE m.section_id = ?
     ORDER BY m.question_id`,
    [sectionId]
  );
  return rows.map((r) => Number(r.question_id));
}

export async function getSectionAnchorQuestionId(conn, sectionId) {
  const ids = await getSectionQuestionIds(conn, sectionId);
  return ids[0] ?? null;
}

export async function requireSectionAnchorQuestionId(conn, sectionId) {
  const questionId = await getSectionAnchorQuestionId(conn, sectionId);
  if (!questionId) {
    throw new ApiError(
      400,
      `Section ${sectionId} has no mapped questions. Map at least one question to this section.`
    );
  }
  return questionId;
}

/** Section treated as done when any answer exists for a question in that section. */
export async function isSectionCompleted(conn, submissionId, sectionId) {
  const [rows] = await conn.query(
    `SELECT 1
     FROM ptw_answers a
     INNER JOIN ptw_section_question_map m ON m.question_id = a.question_id
     WHERE a.submission_id = ? AND m.section_id = ?
     LIMIT 1`,
    [submissionId, sectionId]
  );
  return rows.length > 0;
}
