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

const r = Router();

// GET /api/lookup?pick=org,project,category,subcategory,volume,permission
r.get("/", async (req, res) => {
  const picks = new Set(
    String(
      req.query.pick || "org,project,category,subcategory,volume,permission"
    )
      .split(",")
      .map((s) => s.trim().toLowerCase())
      .filter(Boolean)
  );

  const out = {};

  // Organizations — GLOBAL (อ่านได้ด้วย organizations.view)
  if (picks.has("org")) {
    try {
      // มี perm ไหม? (GLOBAL)
      const ok =
        req.principal?.is_superadmin ||
        req.principal?.permissions?.has?.("organizations.view");
      out.organizations = ok
        ? (
            await sql.query(
              "SELECT org_id, org_name FROM organizations ORDER BY org_name"
            )
          )[0]
        : [];
    } catch {
      out.organizations = [];
    }
  }

  // Projects — ORG scope (projects.view)
  if (picks.has("project")) {
    try {
      const ok =
        req.principal?.is_superadmin ||
        req.principal?.permissions?.has?.("projects.view");
      if (!ok) out.projects = [];
      else {
        // จำกัดตาม org scope
        const p = req.principal;
        let rows = [];
        if (p.is_superadmin) {
          [rows] = await sql.query(
            "SELECT project_id, org_id, project_code, project_name FROM projects ORDER BY project_name"
          );
        } else if (p.org_ids?.length) {
          const inSql = p.org_ids.map(() => "?").join(",");
          [rows] = await sql.query(
            `SELECT project_id, org_id, project_code, project_name
             FROM projects WHERE org_id IN (${inSql})
             ORDER BY project_name`,
            p.org_ids
          );
        } else {
          rows = [];
        }
        out.projects = rows;
      }
    } catch {
      out.projects = [];
    }
  }

  // Categories/Subcategories/Volumes — GLOBAL master (settings.manage ไม่จำเป็นสำหรับการอ่าน lookup)
  if (picks.has("category")) {
    try {
      out.categories = (
        await sql.query(
          "SELECT cat_id, cat_code, cat_name FROM categories ORDER BY cat_name"
        )
      )[0];
    } catch {
      out.categories = [];
    }
  }
  if (picks.has("subcategory")) {
    try {
      out.subcategories = (
        await sql.query(
          "SELECT sub_cat_id, cat_id, sub_cat_name FROM subcategories ORDER BY sub_cat_name"
        )
      )[0];
    } catch {
      out.subcategories = [];
    }
  }
  if (picks.has("volume")) {
    try {
      out.volumes = (
        await sql.query(
          "SELECT volume_id, volume_code, volume_name FROM volumes ORDER BY volume_code"
        )
      )[0];
    } catch {
      out.volumes = [];
    }
  }

  // Permissions — GLOBAL (settings.manage เท่านั้นที่ควรเห็นทั้งหมด)
  if (picks.has("permission")) {
    const ok =
      req.principal?.is_superadmin ||
      req.principal?.permissions?.has?.("settings.manage");
    out.permissions = ok
      ? (
          await sql.query(
            "SELECT permission_id, perm_code AS permission_code, description FROM permissions ORDER BY perm_code"
          )
        )[0]
      : [];
  }

  res.json(out);
});

export default r;
