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

router.get("/notices", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { audience } = req.query;
  let sql = "SELECT * FROM notices WHERE 1=1";
  const params = [];
  if (audience) { sql += " AND (audience='all' OR audience=?)"; params.push(audience); }
  sql += " ORDER BY pinned DESC, created_at DESC";
  const rows = await query(sql, params);
  res.json(rows.map(r => ({ ...r, pinned: !!r.pinned })));
});

router.post("/notices", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { title, body, audience, pinned } = req.body;
  if (!title || !body) return res.status(400).json({ error: "title and body required" });
  const id = await insert("INSERT INTO notices (title, body, audience, pinned, created_by) VALUES (?,?,?,?,?)",
    [title, body, audience ?? "all", pinned ? 1 : 0, session.displayName]);
  res.json({ id, title, body, audience: audience ?? "all", pinned: !!pinned });
});

router.put("/notices/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { title, body, audience, pinned } = req.body;
  await update("UPDATE notices SET title=?, body=?, audience=?, pinned=? WHERE id=?",
    [title, body, audience ?? "all", pinned ? 1 : 0, req.params.id]);
  res.json({ updated: true });
});

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

module.exports = router;
