// FILE: backend/src/routes/organizations.js
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// LIST
r.get("/", requirePerm("organizations.view"), async (_req, res) => {
  const [rows] = await sql.query(
    "SELECT * FROM organizations ORDER BY org_name"
  );
  res.json(rows);
});

// GET
r.get("/:id", requirePerm("organizations.view"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query(
    "SELECT * FROM organizations WHERE org_id=?",
    [id]
  );
  if (!row) return res.status(404).json({ error: "Not found" });
  res.json(row);
});

// CREATE / UPDATE / DELETE — settings.manage
r.post("/", requirePerm("settings.manage"), async (req, res) => {
  const { org_name } = req.body || {};
  if (!org_name) return res.status(400).json({ error: "org_name required" });
  const [rs] = await sql.query(
    "INSERT INTO organizations (org_name) VALUES (?)",
    [org_name]
  );
  res.status(201).json({ org_id: rs.insertId });
});
r.put("/:id", requirePerm("settings.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const { org_name } = req.body || {};
  await sql.query("UPDATE organizations SET org_name=? WHERE org_id=?", [
    org_name,
    id,
  ]);
  res.json({ ok: 1 });
});
r.delete("/:id", requirePerm("settings.manage"), async (req, res) => {
  const id = Number(req.params.id);
  await sql.query("DELETE FROM organizations WHERE org_id=?", [id]);
  res.json({ ok: 1 });
});

export default r;
