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

const r = Router();

// ME (ทุกคน)
r.get("/me", async (req, res) => {
  const p = req.principal;
  const [[u]] = await sql.query(
    `SELECT user_id, username, email, first_name, last_name, org_id FROM users WHERE user_id=?`,
    [p.user_id]
  );
  if (!u) return res.status(404).json({ error: "User not found" });
  const [roles] = await sql.query(
    `SELECT 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=?`,
    [p.user_id]
  );
  res.json({
    ...u,
    roles,
    role_codes: roles.map((r) => r.role_code),
    permissions: [...(p.permissions || [])],
    project_ids: p.project_ids,
    org_ids: p.org_ids,
    is_superadmin: p.is_superadmin,
  });
});

// USERS LIST (ORG scope) — admin.access
r.get(
  "/",
  requirePerm("admin.access", { orgParam: "org_id" }),
  async (req, res) => {
    const P = req.principal;
    let rows = [];
    if (P.is_superadmin) {
      [rows] = await sql.query(
        "SELECT user_id, username, email, org_id FROM users ORDER BY user_id DESC LIMIT 500"
      );
    } else if (P.org_ids?.length) {
      const inSql = P.org_ids.map(() => "?").join(",");
      [rows] = await sql.query(
        `SELECT user_id, username, email, org_id FROM users WHERE org_id IN (${inSql}) ORDER BY user_id DESC LIMIT 500`,
        P.org_ids
      );
    }
    res.json(rows);
  }
);

export default r;
