"use strict";
const { Router } = require("express");
const { query } = require("../db");
const { createSession, destroySession, getSession, getSessionToken, hashPassword, verifyPassword, COOKIE, COOKIE_OPTS } = require("../auth");
const router = Router();

router.post("/auth/login", async (req, res) => {
  const { role, username, password } = req.body || {};
  if (!role || !password) return res.status(400).json({ error: "role and password required" });

  let session = null;

  if (role === "admin" || role === "developer") {
    const [cred] = await query("SELECT * FROM credentials WHERE role = ? LIMIT 1", [role]);
    if (!cred || !verifyPassword(password, cred.password_hash)) {
      return res.status(401).json({ error: "Invalid credentials" });
    }
    session = { role, displayName: role === "admin" ? "Administrator" : "Developer", userId: null };
  } else if (role === "teacher") {
    const name = (username || "").trim();
    if (!name || !password) return res.status(400).json({ error: "Teacher name and password required" });
    session = { role: "teacher", displayName: name, userId: null };
  } else if (role === "student") {
    const sid = (username || "").trim();
    if (!sid) return res.status(400).json({ error: "Student ID required" });
    const [student] = await query("SELECT s.*, c.name AS class_name FROM students s LEFT JOIN classes c ON c.id = s.class_id WHERE s.student_id = ? LIMIT 1", [sid]);
    if (!student || password !== student.student_id) {
      return res.status(401).json({ error: "Invalid student credentials" });
    }
    session = {
      role: "student",
      displayName: `${student.first_name} ${student.last_name}${student.class_name ? " — " + student.class_name : ""}`,
      userId: student.id,
    };
  } else {
    return res.status(400).json({ error: "Unsupported role" });
  }

  const token = createSession(session);
  res.cookie(COOKIE, token, COOKIE_OPTS);
  res.json(session);
});

router.post("/auth/logout", (req, res) => {
  destroySession(getSessionToken(req));
  res.clearCookie(COOKIE, { path: "/" });
  res.status(204).end();
});

router.get("/auth/me", (req, res) => {
  const session = getSession(req);
  if (!session) return res.json({ role: "guest", displayName: "Guest", userId: null });
  res.json(session);
});

router.patch("/auth/password", async (req, res) => {
  const { role, currentPassword, newPassword } = req.body || {};
  const session = getSession(req);
  if (!session || (session.role !== role && session.role !== "developer")) {
    return res.status(403).json({ error: "Forbidden" });
  }
  if (!newPassword || newPassword.length < 4) {
    return res.status(400).json({ error: "Password must be at least 4 characters" });
  }
  const [cred] = await query("SELECT * FROM credentials WHERE role = ? LIMIT 1", [role]);
  if (!cred) return res.status(404).json({ error: "Role not found" });
  if (session.role === role) {
    if (!currentPassword || !verifyPassword(currentPassword, cred.password_hash)) {
      return res.status(401).json({ error: "Current password is incorrect" });
    }
  }
  await query("UPDATE credentials SET password_hash = ? WHERE role = ?", [hashPassword(newPassword), role]);
  res.status(204).end();
});

module.exports = router;
