// FILE: src/routes/categories.js
// อ่าน: ใช้ organizations.view (GLOBAL)
// สร้าง/แก้/ลบ: ใช้ settings.manage (GLOBAL)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// Categories
r.get("/categories", requirePerm("organizations.view"), async (_req, res) => {
  const [rows] = await sql.query(
    "SELECT * FROM categories ORDER BY cat_id DESC"
  );
  res.json(rows);
});
r.post("/categories", requirePerm("settings.manage"), async (req, res) => {
  const { cat_code, cat_name } = req.body || {};
  if (!cat_code || !cat_name)
    return res.status(400).json({ error: "cat_code and cat_name required" });
  const [rs] = await sql.query(
    "INSERT INTO categories (cat_code, cat_name) VALUES (?,?)",
    [cat_code, cat_name]
  );
  res.json({ cat_id: rs.insertId });
});
r.put("/categories/:id", requirePerm("settings.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const { cat_name } = req.body || {};
  await sql.query("UPDATE categories SET cat_name=? WHERE cat_id=?", [
    cat_name,
    id,
  ]);
  res.json({ ok: 1 });
});
r.delete(
  "/categories/:id",
  requirePerm("settings.manage"),
  async (req, res) => {
    const id = Number(req.params.id);
    await sql.query("DELETE FROM categories WHERE cat_id=?", [id]);
    res.json({ ok: 1 });
  }
);

// Subcategories
r.get("/subcategories", requirePerm("organizations.view"), async (req, res) => {
  const { cat_id } = req.query;
  const params = [];
  let where = "";
  if (cat_id) {
    where = " WHERE cat_id=?";
    params.push(Number(cat_id));
  }
  const [rows] = await sql.query(
    `SELECT * FROM subcategories${where} ORDER BY sub_cat_id DESC`,
    params
  );
  res.json(rows);
});

export default r;
