"use strict";
const { Router } = require("express");
const { query } = require("../db");
const router = Router();

function parseQ(r) {
  return {
    ...r,
    options: r.options ? (typeof r.options === "string" ? JSON.parse(r.options) : r.options) : [],
    subjectId: r.subject_id,
    correctAnswer: r.correct_answer,
    createdAt: r.created_at,
  };
}

router.get("/questions", async (req, res) => {
  const { subjectId, type } = req.query;
  let sql = "SELECT * FROM questions";
  const params = []; const where = [];
  if (subjectId) { where.push("subject_id = ?"); params.push(parseInt(subjectId)); }
  if (type) { where.push("type = ?"); params.push(type); }
  if (where.length) sql += " WHERE " + where.join(" AND ");
  sql += " ORDER BY id DESC";
  const rows = await query(sql, params);
  res.json(rows.map(parseQ));
});

router.post("/questions", async (req, res) => {
  const { subjectId, type, prompt, options, correctAnswer, marks, difficulty, explanation } = req.body || {};
  if (!subjectId || !type || !prompt) return res.status(400).json({ error: "subjectId, type, prompt required" });
  await query("INSERT INTO questions (subject_id, type, prompt, options, correct_answer, marks, difficulty, explanation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
    [subjectId, type, prompt, JSON.stringify(options || []), correctAnswer || null, marks || 1, difficulty || null, explanation || null]);
  const [row] = await query("SELECT * FROM questions WHERE id = LAST_INSERT_ID()");
  res.status(201).json(parseQ(row));
});

router.patch("/questions/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.status(400).json({ error: "Invalid id" });
  const { prompt, options, correctAnswer, marks, difficulty, explanation } = req.body || {};
  const sets = []; const vals = [];
  if (prompt !== undefined) { sets.push("prompt = ?"); vals.push(prompt); }
  if (options !== undefined) { sets.push("options = ?"); vals.push(JSON.stringify(options)); }
  if (correctAnswer !== undefined) { sets.push("correct_answer = ?"); vals.push(correctAnswer); }
  if (marks !== undefined) { sets.push("marks = ?"); vals.push(marks); }
  if (difficulty !== undefined) { sets.push("difficulty = ?"); vals.push(difficulty); }
  if (explanation !== undefined) { sets.push("explanation = ?"); vals.push(explanation); }
  if (!sets.length) return res.status(400).json({ error: "Nothing to update" });
  vals.push(id);
  await query(`UPDATE questions SET ${sets.join(", ")} WHERE id = ?`, vals);
  const [row] = await query("SELECT * FROM questions WHERE id = ?", [id]);
  if (!row) return res.status(404).json({ error: "Not found" });
  res.json(parseQ(row));
});

router.delete("/questions/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.status(400).json({ error: "Invalid id" });
  await query("DELETE FROM exam_questions WHERE question_id = ?", [id]);
  await query("DELETE FROM questions WHERE id = ?", [id]);
  res.status(204).end();
});

module.exports = router;
