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

router.get("/calendar", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { month, year } = req.query;
  let sql = "SELECT * FROM calendar_events WHERE (target_role='all' OR target_role=?)";
  const params = [session.role];
  if (month && year) {
    const start = `${year}-${month.toString().padStart(2,"0")}-01`;
    const end = `${year}-${month.toString().padStart(2,"0")}-31`;
    sql += " AND date BETWEEN ? AND ?";
    params.push(start, end);
  }
  sql += " ORDER BY date ASC";
  res.json(await query(sql, params));
});

router.post("/calendar", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { title, date, endDate, type, description, color, targetRole } = req.body;
  if (!title || !date) return res.status(400).json({ error: "title and date required" });
  const id = await insert("INSERT INTO calendar_events (title, date, end_date, type, description, color, target_role, created_by) VALUES (?,?,?,?,?,?,?,?)",
    [title, date, endDate || "", type || "event", description || "", color || "#3b82f6", targetRole || "all", session.displayName]);
  res.json({ id, title, date });
});

router.put("/calendar/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { title, date, endDate, type, description, color, targetRole } = req.body;
  await update("UPDATE calendar_events SET title=?, date=?, end_date=?, type=?, description=?, color=?, target_role=? WHERE id=?",
    [title, date, endDate || "", type || "event", description || "", color || "#3b82f6", targetRole || "all", req.params.id]);
  res.json({ updated: true });
});

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

module.exports = router;
