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

router.get("/library/books", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { category, search } = req.query;
  let sql = "SELECT * FROM library_books WHERE 1=1";
  const params = [];
  if (category) { sql += " AND category=?"; params.push(category); }
  if (search) { sql += " AND (title LIKE ? OR author LIKE ? OR isbn LIKE ?)"; params.push(`%${search}%`, `%${search}%`, `%${search}%`); }
  sql += " ORDER BY title ASC";
  res.json(await query(sql, params));
});

router.post("/library/books", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { title, author, isbn, category, quantity, description, coverUrl } = req.body;
  if (!title) return res.status(400).json({ error: "title required" });
  const qty = parseInt(quantity) || 1;
  const id = await insert("INSERT INTO library_books (title, author, isbn, category, quantity, available, description, cover_url, added_by) VALUES (?,?,?,?,?,?,?,?,?)",
    [title, author || "", isbn || "", category || "General", qty, qty, description || "", coverUrl || "", session.displayName]);
  res.json({ id, title, author, isbn, category, quantity: qty, available: qty });
});

router.put("/library/books/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { title, author, isbn, category, quantity, description, coverUrl } = req.body;
  await update("UPDATE library_books SET title=?, author=?, isbn=?, category=?, quantity=?, description=?, cover_url=? WHERE id=?",
    [title, author || "", isbn || "", category || "General", parseInt(quantity) || 1, description || "", coverUrl || "", req.params.id]);
  res.json({ updated: true });
});

router.delete("/library/books/: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 library_books WHERE id=?", [req.params.id]);
  res.json({ deleted: true });
});

router.get("/library/borrowings", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { studentId, status } = req.query;
  let sql = `SELECT lb.*, b.title as book_title, b.author as book_author,
    CONCAT(s.first_name,' ',s.last_name) as student_name
    FROM library_borrowings lb
    LEFT JOIN library_books b ON lb.book_id=b.id
    LEFT JOIN students s ON lb.student_id=s.id WHERE 1=1`;
  const params = [];
  if (studentId) { sql += " AND lb.student_id=?"; params.push(studentId); }
  if (status) { sql += " AND lb.status=?"; params.push(status); }
  sql += " ORDER BY lb.borrowed_at DESC";
  res.json(await query(sql, params));
});

router.post("/library/borrow", async (req, res) => {
  const session = getSession(req);
  if (!session || (session.role !== "admin" && session.role !== "teacher")) return res.status(403).json({ error: "Staff only" });
  const { bookId, studentId, dueDate } = req.body;
  if (!bookId || !studentId || !dueDate) return res.status(400).json({ error: "bookId, studentId, dueDate required" });
  const [book] = await query("SELECT * FROM library_books WHERE id=?", [bookId]);
  if (!book) return res.status(404).json({ error: "Book not found" });
  if (book.available <= 0) return res.status(400).json({ error: "No copies available" });
  const id = await insert("INSERT INTO library_borrowings (book_id, student_id, due_date, status, processed_by) VALUES (?,?,?,?,?)",
    [bookId, studentId, dueDate, "borrowed", session.displayName]);
  await update("UPDATE library_books SET available=available-1 WHERE id=?", [bookId]);
  res.json({ id });
});

router.post("/library/return/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || (session.role !== "admin" && session.role !== "teacher")) return res.status(403).json({ error: "Staff only" });
  const [borrowing] = await query("SELECT * FROM library_borrowings WHERE id=?", [req.params.id]);
  if (!borrowing) return res.status(404).json({ error: "Not found" });
  await update("UPDATE library_borrowings SET status='returned', returned_at=NOW(), processed_by=? WHERE id=?",
    [session.displayName, req.params.id]);
  await update("UPDATE library_books SET available=available+1 WHERE id=?", [borrowing.book_id]);
  res.json({ returned: true });
});

module.exports = router;
