const asyncHandler = require('../middlewares/asyncHandler');
const {
  getAllQuestions,
  getQuestionById,
  createQuestion,
  updateQuestion,
  deleteQuestion
} = require('../repositories/questionsRepository');

// Get all sat_questions
exports.getAllQuestions = asyncHandler(async (req, res) => {
    const rows = await getAllQuestions();
    res.status(200).json({ success: true, data: rows });
});

// Get question by ID
exports.getQuestionById = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const question = await getQuestionById(id);
    
    if (!question) {
        return res.status(404).json({ success: false, message: 'Question not found' });
    }
    
    res.status(200).json({ success: true, data: question });
});

// Create question
exports.createQuestion = asyncHandler(async (req, res) => {
    const { question, question_type_id, allows_media, options } = req.body;
    
    if (!question || !question_type_id) {
        return res.status(400).json({ success: false, message: 'question and question_type_id are required' });
    }
    
    const questionId = await createQuestion(
        question,
        question_type_id,
        allows_media,
        Array.isArray(options) ? options : undefined
    );
    res.status(201).json({ success: true, message: 'Question created successfully', data: { question_id: questionId } });
});

// Update question
exports.updateQuestion = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { question, question_type_id, allows_media, options } = req.body;
    
    const updateData = {};
    if (question !== undefined) updateData.question = question;
    if (question_type_id !== undefined) updateData.question_type_id = question_type_id;
    if (allows_media !== undefined) updateData.allows_media = allows_media;
    if (options !== undefined) updateData.options = Array.isArray(options) ? options : null;
    
    if (Object.keys(updateData).length === 0) {
        return res.status(400).json({ success: false, message: 'No fields to update' });
    }
    
    const updated = await updateQuestion(id, updateData);
    
    if (!updated) {
        return res.status(404).json({ success: false, message: 'Question not found' });
    }
    
    res.status(200).json({ success: true, message: 'Question updated successfully' });
});

// Delete question
exports.deleteQuestion = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const deleted = await deleteQuestion(id);
    
    if (!deleted) {
        return res.status(404).json({ success: false, message: 'Question not found' });
    }
    
    res.status(200).json({ success: true, message: 'Question deleted successfully' });
});

