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

async function enrichTT(rows) {
  if (!rows.length) return rows;
  const classes = await query("SELECT id, name FROM classes");
  const subjects = await query("SELECT id, name FROM subjects");
  const cMap = new Map(classes.map(c => [c.id, c.name]));
  const sMap = new Map(subjects.map(s => [s.id, s.name]));
  return rows.map(r => ({
    id: r.id, classId: r.class_id, subjectId: r.subject_id,
    date: r.date, startTime: r.start_time, endTime: r.end_time,
    venue: r.venue, teacher: r.teacher, term: r.term,
    className: cMap.get(r.class_id) ?? null,
    subjectName: sMap.get(r.subject_id) ?? null,
  }));
}

router.get("/timetable", async (req, res) => {
  const { classId, term } = req.query;
  let sql = "SELECT * FROM timetable_entries";
  const params = []; const where = [];
  if (classId) { where.push("class_id = ?"); params.push(parseInt(classId)); }
  if (term) { where.push("term = ?"); params.push(term); }
  if (where.length) sql += " WHERE " + where.join(" AND ");
  sql += " ORDER BY date, start_time";
  const rows = await query(sql, params);
  res.json(await enrichTT(rows));
});

router.post("/timetable", async (req, res) => {
  const { classId, subjectId, date, startTime, endTime, venue, teacher, term } = req.body || {};
  if (!classId || !subjectId || !date || !startTime || !endTime || !venue || !teacher || !term) {
    return res.status(400).json({ error: "All fields required" });
  }
  await query("INSERT INTO timetable_entries (class_id, subject_id, date, start_time, end_time, venue, teacher, term) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
    [classId, subjectId, date, startTime, endTime, venue, teacher, term]);
  const [row] = await query("SELECT * FROM timetable_entries WHERE id = LAST_INSERT_ID()");
  const [enriched] = await enrichTT([row]);
  res.status(201).json(enriched);
});

router.patch("/timetable/:id", async (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.status(400).json({ error: "Invalid id" });
  const { classId, subjectId, date, startTime, endTime, venue, teacher, term } = req.body || {};
  const sets = []; const vals = [];
  if (classId !== undefined) { sets.push("class_id = ?"); vals.push(classId); }
  if (subjectId !== undefined) { sets.push("subject_id = ?"); vals.push(subjectId); }
  if (date !== undefined) { sets.push("date = ?"); vals.push(date); }
  if (startTime !== undefined) { sets.push("start_time = ?"); vals.push(startTime); }
  if (endTime !== undefined) { sets.push("end_time = ?"); vals.push(endTime); }
  if (venue !== undefined) { sets.push("venue = ?"); vals.push(venue); }
  if (teacher !== undefined) { sets.push("teacher = ?"); vals.push(teacher); }
  if (term !== undefined) { sets.push("term = ?"); vals.push(term); }
  if (!sets.length) return res.status(400).json({ error: "Nothing to update" });
  vals.push(id);
  await query(`UPDATE timetable_entries SET ${sets.join(", ")} WHERE id = ?`, vals);
  const [row] = await query("SELECT * FROM timetable_entries WHERE id = ?", [id]);
  if (!row) return res.status(404).json({ error: "Not found" });
  const [enriched] = await enrichTT([row]);
  res.json(enriched);
});

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

module.exports = router;
