// FILE: backend/src/routes/mvp.js
// (generic entity maps — ใช้ ‘projects.view’ อ่าน และ ‘projects.manage’ เขียน/ลบ)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// LIST — projects.view (ORG scope)
r.get(
  "/",
  requirePerm("projects.view", { orgParam: "org_id" }),
  async (req, res) => {
    const {
      project_id,
      org_id,
      module,
      src_type,
      dst_type,
      limit = 100,
      offset = 0,
    } = req.query;
    const p = req.principal;
    const params = [];
    const cond = [];

    if (!p.is_superadmin) {
      if (org_id) {
        if (!p.inOrg(Number(org_id)))
          return res.status(403).json({ error: "FORBIDDEN_ORG" });
        cond.push("m.org_id=?");
        params.push(Number(org_id));
      } else if (p.org_ids?.length) {
        cond.push(`m.org_id IN (${p.org_ids.map(() => "?").join(",")})`);
        params.push(...p.org_ids);
      }
    } else if (org_id) {
      cond.push("m.org_id=?");
      params.push(Number(org_id));
    }

    if (project_id) {
      cond.push("m.project_id=?");
      params.push(Number(project_id));
    }
    if (module) {
      cond.push("m.module=?");
      params.push(module);
    }
    if (src_type) {
      cond.push("m.src_type=?");
      params.push(src_type);
    }
    if (dst_type) {
      cond.push("m.dst_type=?");
      params.push(dst_type);
    }

    const where = cond.length ? `WHERE ${cond.join(" AND ")}` : "";
    const [rows] = await sql.query(
      `SELECT m.* FROM entity_maps m ${where} ORDER BY m.id DESC LIMIT ? OFFSET ?`,
      [...params, Number(limit), Number(offset)]
    );
    res.json(rows);
  }
);

// CREATE — projects.manage (ORG scope)
r.post(
  "/",
  requirePerm("projects.manage", { orgParam: "org_id" }),
  async (req, res) => {
    const {
      org_id,
      project_id,
      module,
      src_type,
      src_id,
      dst_type,
      dst_id,
      remark,
    } = req.body || {};
    if (!org_id || !project_id || !module)
      return res
        .status(400)
        .json({ error: "org_id, project_id, module required" });
    const [rs] = await sql.query(
      `INSERT INTO entity_maps (org_id, project_id, module, src_type, src_id, dst_type, dst_id, remark, created_by)
       VALUES (?,?,?,?,?,?,?,?,?)`,
      [
        Number(org_id),
        Number(project_id),
        module,
        src_type || null,
        src_id ? Number(src_id) : null,
        dst_type || null,
        dst_id ? Number(dst_id) : null,
        remark || null,
        req.principal.user_id,
      ]
    );
    res.json({ id: rs.insertId });
  }
);

// DELETE — projects.manage (ORG scope)
r.delete(
  "/:id",
  requirePerm("projects.manage", { orgParam: "org_id" }),
  async (req, res) => {
    const id = Number(req.params.id);
    await sql.query("DELETE FROM entity_maps WHERE id=?", [id]);
    res.json({ ok: 1 });
  }
);

export default r;
