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

router.get("/classes", async (_req, res) => {
  const rows = await query("SELECT * FROM classes ORDER BY name");
  res.json(rows.map(r => ({ ...r, createdAt: r.created_at })));
});

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

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

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

module.exports = router;
