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

const r = Router();

/**
 * GET /api/admin/sysinfo
 * perm: admin.access (ORG scope) – ใช้สิทธิ์กลุ่ม admin
 */
r.get(
  "/sysinfo",
  requirePerm("admin.access", { orgParam: "org_id" }),
  async (_req, res) => {
    try {
      await sql.query("SELECT 1");
      res.json({
        now: new Date().toISOString(),
        node: process.version,
        platform: os.platform(),
        arch: os.arch(),
        cpus: os.cpus()?.length,
        uptime_sec: os.uptime(),
        loadavg: os.loadavg(),
        memory: { total: os.totalmem(), free: os.freemem() },
        env: {
          NODE_ENV: process.env.NODE_ENV,
          APP_VERSION: process.env.APP_VERSION,
        },
      });
    } catch (e) {
      res.status(500).json({ error: "SYSINFO_FAIL", message: e?.message });
    }
  }
);

/**
 * POST /api/admin/maintenance/reindex
 * perm: settings.manage (GLOBAL) – งานดูแลระบบ
 */
r.post(
  "/maintenance/reindex",
  requirePerm("settings.manage"),
  async (_req, res) => {
    try {
      // ปรับตามตารางจริงของคุณ
      await sql.query("ANALYZE TABLE correspondences, rfas, drawings");
      res.json({ ok: 1 });
    } catch (e) {
      res.status(500).json({ error: "MAINT_FAIL", message: e?.message });
    }
  }
);

/**
 * GET /api/admin/perm-matrix?format=json
 * perm: admin.access (ORG)
 */
r.get(
  "/perm-matrix",
  requirePerm("admin.access", { orgParam: "org_id" }),
  async (req, res) => {
    const format = String(req.query.format || "json").toLowerCase();
    const [roles] = await sql.query(
      `SELECT r.role_id, r.role_code, r.role_name,
            GROUP_CONCAT(p.perm_code ORDER BY p.perm_code SEPARATOR ', ') AS perm_codes
       FROM roles r
       LEFT JOIN role_permissions rp ON rp.role_id = r.role_id
       LEFT JOIN permissions p ON p.permission_id = rp.permission_id
      GROUP BY r.role_id, r.role_code, r.role_name
      ORDER BY r.role_code`
    );
    if (format === "json") return res.json({ roles });
    // markdown แบบง่าย
    const lines = [
      `# Permission Matrix`,
      `_Generated at: ${new Date().toISOString()}_`,
      `| # | Role Code | Role Name | Permissions |`,
      `|---:|:---------|:----------|:------------|`,
      ...roles.map(
        (r, i) =>
          `| ${i + 1} | \`${r.role_code}\` | ${r.role_name || ""} | ${
            r.perm_codes || ""
          } |`
      ),
    ];
    res.setHeader("Content-Type", "text/markdown; charset=utf-8");
    res.send(lines.join("\n"));
  }
);

export default r;
