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

/**
 * Loads `orac_combined_question` and builds lookup maps (main → children, child → main).
 */
export async function loadCombinedQuestionMaps() {
  const [rows] = await pool.query(
    "SELECT `main_question_id`, `child_question_id` FROM `orac_combined_question` ORDER BY `main_question_id` ASC, `child_question_id` ASC"
  );
  /** @type {Map<number, number[]>} */
  const childrenByMain = new Map();
  /** @type {Map<number, number>} */
  const mainByChild = new Map();
  for (const r of rows) {
    const m = Number(r.main_question_id);
    const c = Number(r.child_question_id);
    if (!Number.isInteger(m) || !Number.isInteger(c)) continue;
    if (!childrenByMain.has(m)) childrenByMain.set(m, []);
    childrenByMain.get(m).push(c);
    mainByChild.set(c, m);
  }
  return { childrenByMain, mainByChild };
}

/**
 * @param {object} q - Question row (must have `question_id`)
 * @param {{ childrenByMain: Map<number, number[]>, mainByChild: Map<number, number> }} maps
 */
export function attachCombinedMetadata(q, maps) {
  const id = q.question_id;
  const children = maps.childrenByMain.get(id);
  const main = maps.mainByChild.get(id);
  return {
    ...q,
    child_question_ids: children && children.length ? children : [],
    main_question_id: main != null ? main : null
  };
}

export function enrichQuestionRows(rows, maps) {
  return rows.map((q) => attachCombinedMetadata(q, maps));
}
