// FILE: backend/src/routes/subcategories.js
// Master data: subcategories — GLOBAL read/write (ตาม categories.js)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// LIST (GLOBAL read)
r.get(
  "/sub_categories",
  requirePerm("organizations.view"),
  async (req, res) => {
    const { q, cat_id, page = 1, page_size = 50 } = req.query;
    const limit = Math.min(Number(page_size) || 50, 200);
    const offset = (Math.max(Number(page) || 1, 1) - 1) * limit;

    const cond = [];
    const params = [];
    if (cat_id) {
      cond.push("cat_id=?");
      params.push(Number(cat_id));
    }
    if (q) {
      cond.push("LOWER(sub_cat_name) LIKE ?");
      params.push(`%${String(q).toLowerCase()}%`);
    }

    const where = cond.length ? `WHERE ${cond.join(" AND ")}` : "";
    const [[{ cnt }]] = await sql.query(
      `SELECT COUNT(*) AS cnt FROM subcategories ${where}`,
      params
    );
    const [rows] = await sql.query(
      `SELECT * FROM subcategories ${where} ORDER BY sub_cat_name ASC LIMIT ? OFFSET ?`,
      [...params, limit, offset]
    );
    res.json({
      items: rows,
      total: Number(cnt || 0),
      page: Number(page) || 1,
      page_size: limit,
    });
  }
);

// CREATE (GLOBAL write)
r.post("/sub_categories", requirePerm("settings.manage"), async (req, res) => {
  const { cat_id, sub_cat_name, code } = req.body || {};
  if (!cat_id || !sub_cat_name)
    return res.status(400).json({ error: "cat_id and sub_cat_name required" });
  const [rs] = await sql.query(
    "INSERT INTO subcategories (cat_id, sub_cat_name, code) VALUES (?,?,?)",
    [Number(cat_id), sub_cat_name, code ?? null]
  );
  res.status(201).json({ sub_cat_id: rs.insertId });
});

// UPDATE
r.patch(
  "/sub_categories/:id",
  requirePerm("settings.manage"),
  async (req, res) => {
    const id = Number(req.params.id);
    const [[row]] = await sql.query(
      "SELECT * FROM subcategories WHERE sub_cat_id=?",
      [id]
    );
    if (!row) return res.status(404).json({ error: "Not found" });
    const { sub_cat_name, cat_id, code } = req.body || {};
    await sql.query(
      "UPDATE subcategories SET sub_cat_name=?, cat_id=?, code=? WHERE sub_cat_id=?",
      [
        sub_cat_name ?? row.sub_cat_name,
        cat_id ?? row.cat_id,
        code ?? row.code,
        id,
      ]
    );
    res.json({ ok: true });
  }
);

// DELETE
r.delete(
  "/sub_categories/:id",
  requirePerm("settings.manage"),
  async (req, res) => {
    const id = Number(req.params.id);
    await sql.query("DELETE FROM subcategories WHERE sub_cat_id=?", [id]);
    res.json({ ok: true });
  }
);

export default r;
