const pool = require('../config/db');

const getOptionsByQuestionId = async (questionId) => {
  const [rows] = await pool.query(
    'SELECT _options FROM sat_question_options WHERE question_id = ?',
    [questionId]
  );
  return rows.map(r => r._options);
};

const getOptionsByQuestionIds = async (questionIds) => {
  if (!questionIds || questionIds.length === 0) return {};
  const placeholders = questionIds.map(() => '?').join(',');
  const [rows] = await pool.query(
    `SELECT question_id, _options FROM sat_question_options WHERE question_id IN (${placeholders})`,
    questionIds
  );
  const byQuestion = {};
  rows.forEach(row => {
    if (!byQuestion[row.question_id]) byQuestion[row.question_id] = [];
    byQuestion[row.question_id].push(row._options);
  });
  return byQuestion;
};

const insertOptions = async (questionId, options) => {
  if (!questionId || !Array.isArray(options) || options.length === 0) return;
  for (let i = 0; i < options.length; i++) {
    await pool.query(
      'INSERT INTO sat_question_options (question_id, _options) VALUES (?, ?)',
      [questionId, options[i]]
    );
  }
};

const deleteOptionsForQuestion = async (questionId) => {
  await pool.query('DELETE FROM sat_question_options WHERE question_id = ?', [questionId]);
};

module.exports = {
  getOptionsByQuestionId,
  getOptionsByQuestionIds,
  insertOptions,
  deleteOptionsForQuestion
};
