"use strict";
const { Router } = require("express");
const { query, insert, update } = require("../db");
const { getSession } = require("../auth");
const router = Router();

router.get("/teachers", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const rows = await query("SELECT * FROM teachers ORDER BY created_at DESC");
  res.json(rows);
});

router.post("/teachers", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { name, email, phone, qualification, subjects } = req.body;
  if (!name) return res.status(400).json({ error: "name required" });
  const id = await insert("INSERT INTO teachers (name, email, phone, qualification, subjects) VALUES (?,?,?,?,?)",
    [name, email ?? "", phone ?? "", qualification ?? "", JSON.stringify(subjects ?? [])]);
  res.json({ id, name, email, phone, qualification, subjects: subjects ?? [] });
});

router.put("/teachers/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { name, email, phone, qualification, subjects } = req.body;
  await update("UPDATE teachers SET name=?, email=?, phone=?, qualification=?, subjects=? WHERE id=?",
    [name, email ?? "", phone ?? "", qualification ?? "", JSON.stringify(subjects ?? []), req.params.id]);
  res.json({ updated: true });
});

router.delete("/teachers/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  await query("DELETE FROM teachers WHERE id=?", [req.params.id]);
  res.json({ deleted: true });
});

module.exports = router;
