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

async function withClassName(rows) {
  if (!rows.length) return rows;
  const classes = await query("SELECT id, name FROM classes");
  const map = new Map(classes.map(c => [c.id, c.name]));
  return rows.map(r => ({ ...r, className: map.get(r.class_id) ?? null, createdAt: r.created_at }));
}

router.get("/subjects", async (req, res) => {
  const { classId } = req.query;
  let rows;
  if (classId) {
    rows = await query("SELECT * FROM subjects WHERE class_id = ? ORDER BY name", [parseInt(classId)]);
  } else {
    rows = await query("SELECT * FROM subjects ORDER BY name");
  }
  res.json(await withClassName(rows));
});

router.post("/subjects", async (req, res) => {
  const { name, code, classId } = req.body || {};
  if (!name || !code || !classId) return res.status(400).json({ error: "name, code, classId required" });
  await query("INSERT INTO subjects (name, code, class_id) VALUES (?, ?, ?)", [name, code, classId]);
  const [row] = await query("SELECT * FROM subjects WHERE id = LAST_INSERT_ID()");
  const [enriched] = await withClassName([row]);
  res.status(201).json(enriched);
});

router.patch("/subjects/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.status(400).json({ error: "Invalid id" });
  const { name, code, classId } = req.body || {};
  const sets = []; const vals = [];
  if (name !== undefined) { sets.push("name = ?"); vals.push(name); }
  if (code !== undefined) { sets.push("code = ?"); vals.push(code); }
  if (classId !== undefined) { sets.push("class_id = ?"); vals.push(classId); }
  if (!sets.length) return res.status(400).json({ error: "Nothing to update" });
  vals.push(id);
  await query(`UPDATE subjects SET ${sets.join(", ")} WHERE id = ?`, vals);
  const [row] = await query("SELECT * FROM subjects WHERE id = ?", [id]);
  if (!row) return res.status(404).json({ error: "Not found" });
  const [enriched] = await withClassName([row]);
  res.json(enriched);
});

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

module.exports = router;
