const pool = require("../config/db");
const {
  getOptionsByQuestionId,
  getOptionsByQuestionIds,
  insertOptions,
  deleteOptionsForQuestion
} = require("./questionOptionsRepository");
const { getCombinedQuestionsByQuestionIds } = require("./combinedQuestionRepository");

const getAllQuestions = async () => {
  const [rows] = await pool.query(`
    SELECT q.question_id, q.question, q.question_type_id, q.allows_media, qt.question_type 
    FROM sat_questions q
    LEFT JOIN sat_question_type qt ON q.question_type_id = qt.question_type_id
  `);
  const questionIds = rows.map(r => r.question_id).filter(Boolean);
  const optionsMap = questionIds.length ? await getOptionsByQuestionIds(questionIds) : {};
  const combinedRows = await getCombinedQuestionsByQuestionIds(questionIds);
  const mainToChildren = new Map();
  const childToMain = new Map();
  combinedRows.forEach((row) => {
    const mainId = row.main_question_id;
    const childId = row.child_question_id;
    if (!mainToChildren.has(mainId)) mainToChildren.set(mainId, []);
    mainToChildren.get(mainId).push(childId);
    childToMain.set(childId, mainId);
  });
  return rows.map(row => ({
    ...row,
    options: optionsMap[row.question_id] || [],
    child_question_ids: mainToChildren.get(row.question_id) || [],
    main_question_id: childToMain.get(row.question_id) ?? null
  }));
};

const getQuestionById = async (id) => {
  const [rows] = await pool.query(`
    SELECT q.question_id, q.question, q.question_type_id, q.allows_media, qt.question_type 
    FROM sat_questions q
    LEFT JOIN sat_question_type qt ON q.question_type_id = qt.question_type_id
    WHERE q.question_id = ?
  `, [id]);
  if (rows.length === 0) return null;
  const options = await getOptionsByQuestionId(id);
  return { ...rows[0], options };
};

const createQuestion = async (question, question_type_id, allows_media, options = null) => {
  const [result] = await pool.query(
    'INSERT INTO sat_questions (question, question_type_id, allows_media) VALUES (?, ?, ?)',
    [
      question,
      question_type_id,
      allows_media !== undefined ? allows_media : false
    ]
  );
  const questionId = result.insertId;
  if (options && Array.isArray(options) && options.length > 0) {
    await insertOptions(questionId, options);
  }
  return questionId;
};

const updateQuestion = async (id, updateData) => {
  const { question, question_type_id, allows_media, options } = updateData;
  const updateFields = [];
  const updateValues = [];
  
  if (question !== undefined) { updateFields.push('question = ?'); updateValues.push(question); }
  if (question_type_id !== undefined) { updateFields.push('question_type_id = ?'); updateValues.push(question_type_id); }
  if (allows_media !== undefined) { updateFields.push('allows_media = ?'); updateValues.push(allows_media); }
  
  if (updateFields.length > 0) {
    updateValues.push(id);
    await pool.query(
      `UPDATE sat_questions SET ${updateFields.join(', ')} WHERE question_id = ?`,
      updateValues
    );
  }
  
  if (options !== undefined) {
    await deleteOptionsForQuestion(id);
    if (Array.isArray(options) && options.length > 0) {
      await insertOptions(id, options);
    }
  }
  
  return updateFields.length > 0 || options !== undefined;
};

const deleteQuestion = async (id) => {
  const [result] = await pool.query('DELETE FROM sat_questions WHERE question_id = ?', [id]);
  return result.affectedRows > 0;
};

module.exports = {
  getAllQuestions,
  getQuestionById,
  createQuestion,
  updateQuestion,
  deleteQuestion
};

