import { pool } from "../config/db.js";
import { enrichQuestionRows, loadCombinedQuestionMaps } from "../utils/oracCombinedQuestionEnrichment.js";

/**
 * Same filters as `listRecords("orac_questions")`, plus `child_question_ids` / `main_question_id`
 * from `orac_combined_question` for form builder + answering UIs.
 */
export async function listOracQuestionsEnriched(req, res, next) {
  try {
    const filters = req.query || {};
    const whereParts = [];
    const values = [];

    Object.entries(filters).forEach(([key, value]) => {
      if (value === undefined || value === null || value === "") {
        return;
      }
      if (key.endsWith("_like")) {
        const column = key.slice(0, -5);
        whereParts.push(`\`${column}\` LIKE ?`);
        values.push(`%${value}%`);
      } else {
        whereParts.push(`\`${key}\` = ?`);
        values.push(value);
      }
    });

    let sql = "SELECT * FROM `orac_questions`";
    if (whereParts.length) {
      sql += ` WHERE ${whereParts.join(" AND ")}`;
    }

    const [rows] = await pool.query(sql, values);
    const maps = await loadCombinedQuestionMaps();
    res.json(enrichQuestionRows(rows, maps));
  } catch (err) {
    next(err);
  }
}
