import prisma from '../services/prisma.js';
import asyncHandler from '../utils/asyncHandler.js';
import ApiError from '../utils/ApiError.js';
import { explainQuestion, isAiConfigured } from '../services/ai.service.js';

// POST /api/ai/explain  { questionId }
export const explain = asyncHandler(async (req, res) => {
  const { questionId } = req.body;
  if (!questionId) throw ApiError.badRequest('questionId is required');

  const question = await prisma.question.findUnique({
    where: { id: questionId },
    include: { options: { orderBy: { order: 'asc' } } },
  });
  if (!question) throw ApiError.notFound('Question not found');

  const correctTexts = question.options.filter((o) => o.isCorrect).map((o) => o.text);

  const { explanation, generated } = await explainQuestion({
    question: question.text,
    options: question.options.map((o) => o.text),
    correctTexts,
    existingExplanation: question.explanation,
  });

  res.json({ success: true, explanation, generated, aiConfigured: isAiConfigured() });
});
