// FILE: backend/src/routes/rbac_admin.js
// RBAC admin — ใช้ settings.manage ทั้งหมด
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// ROLES
r.get("/roles", requirePerm("settings.manage"), async (_req, res) => {
  const [rows] = await sql.query(
    "SELECT role_id, role_code, role_name, description FROM roles ORDER BY role_code"
  );
  res.json(rows);
});

// PERMISSIONS
r.get("/permissions", requirePerm("settings.manage"), async (_req, res) => {
  const [rows] = await sql.query(
    "SELECT permission_id, perm_code AS permission_code, scope_level, description FROM permissions ORDER BY perm_code"
  );
  res.json(rows);
});

// role -> permissions
r.get(
  "/roles/:role_id/permissions",
  requirePerm("settings.manage"),
  async (req, res) => {
    const role_id = Number(req.params.role_id);
    const [rows] = await sql.query(
      `SELECT p.permission_id, p.perm_code AS permission_code, p.description
     FROM role_permissions rp
     JOIN permissions p ON p.permission_id = rp.permission_id
     WHERE rp.role_id=? ORDER BY p.perm_code`,
      [role_id]
    );
    res.json(rows);
  }
);

r.post(
  "/roles/:role_id/permissions",
  requirePerm("settings.manage"),
  async (req, res) => {
    const role_id = Number(req.params.role_id);
    const { permission_id } = req.body || {};
    await sql.query(
      "INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?,?)",
      [role_id, Number(permission_id)]
    );
    res.json({ ok: 1 });
  }
);

r.delete(
  "/roles/:role_id/permissions/:permission_id",
  requirePerm("settings.manage"),
  async (req, res) => {
    const role_id = Number(req.params.role_id);
    const permission_id = Number(req.params.permission_id);
    await sql.query(
      "DELETE FROM role_permissions WHERE role_id=? AND permission_id=?",
      [role_id, permission_id]
    );
    res.json({ ok: 1 });
  }
);

// user -> roles (global/org/project scope columns มีในตาราง user_roles ตามสคีมา)
r.get(
  "/users/:user_id/roles",
  requirePerm("settings.manage"),
  async (req, res) => {
    const user_id = Number(req.params.user_id);
    const [rows] = await sql.query(
      `SELECT ur.user_id, ur.role_id, r.role_code, r.role_name, ur.org_id, ur.project_id
     FROM user_roles ur JOIN roles r ON r.role_id = ur.role_id
     WHERE ur.user_id=? ORDER BY r.role_code`,
      [user_id]
    );
    res.json(rows);
  }
);

r.post(
  "/users/:user_id/roles",
  requirePerm("settings.manage"),
  async (req, res) => {
    const user_id = Number(req.params.user_id);
    const { role_id, org_id = null, project_id = null } = req.body || {};
    await sql.query(
      "INSERT INTO user_roles (user_id, role_id, org_id, project_id) VALUES (?,?,?,?)",
      [
        user_id,
        Number(role_id),
        org_id ? Number(org_id) : null,
        project_id ? Number(project_id) : null,
      ]
    );
    res.json({ ok: 1 });
  }
);

r.delete(
  "/users/:user_id/roles",
  requirePerm("settings.manage"),
  async (req, res) => {
    const user_id = Number(req.params.user_id);
    const { role_id, org_id = null, project_id = null } = req.body || {};
    // สร้างเงื่อนไขแบบ dynamic สำหรับ NULL-safe compare
    const whereOrg = org_id === null ? "ur.org_id IS NULL" : "ur.org_id = ?";
    const wherePrj =
      project_id === null ? "ur.project_id IS NULL" : "ur.project_id = ?";
    const params = [user_id, Number(role_id)];
    if (org_id !== null) params.push(Number(org_id));
    if (project_id !== null) params.push(Number(project_id));
    await sql.query(
      `DELETE FROM user_roles ur WHERE ur.user_id=? AND ur.role_id=? AND ${whereOrg} AND ${wherePrj}`,
      params
    );
    res.json({ ok: 1 });
  }
);

export default r;
