import { fetchCombinedQuestionByMain, mapQuestionToSection } from '../api.js';

/**
 * Links `question_id` to a section. If that question is a `orac_combined_question` parent
 * (`main_question_id`), also links each `child_question_id` that is not already in `linkedIds`.
 *
 * @param {number} sectionId
 * @param {number} questionId
 * @param {Set<number>} linkedIds - Question IDs already mapped to this section (mutated).
 * @returns {Promise<{ addedChildren: number }>}
 */
export async function mapQuestionToSectionIncludingCombinedChildren(sectionId, questionId, linkedIds) {
  const sid = Number(sectionId);
  const qid = Number(questionId);
  if (!Number.isInteger(sid) || sid <= 0 || !Number.isInteger(qid) || qid <= 0) {
    return { addedChildren: 0 };
  }

  if (!linkedIds.has(qid)) {
    await mapQuestionToSection(sid, qid);
    linkedIds.add(qid);
  }

  const rows = await fetchCombinedQuestionByMain(qid);
  let addedChildren = 0;
  for (const row of rows) {
    const cid = Number(row?.child_question_id);
    if (!Number.isInteger(cid) || cid <= 0) continue;
    if (!linkedIds.has(cid)) {
      await mapQuestionToSection(sid, cid);
      linkedIds.add(cid);
      addedChildren += 1;
    }
  }
  return { addedChildren };
}
