// FILE: src/routes/contract_dwg.js
// ใน seed ยังไม่มี contract_dwg.* → ผูกชั่วคราวกับสิทธิ์กลุ่ม drawings:
// read → drawings.view, create/update/delete → drawings.upload/delete (PROJECT scope)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// LIST (PROJECT scope enforce via params ifส่ง project_id, ไม่ส่งจะถูก filter ด้วย scope ภายใน)
r.get(
  "/",
  requirePerm("drawings.view", { projectParam: "project_id" }),
  async (req, res) => {
    const { project_id, org_id, condwg_no, limit = 50, offset = 0 } = req.query;
    const p = req.principal;
    const params = [];
    const cond = [];

    // ABAC filter ฝั่ง server กันหลุดขอบเขต
    if (!p.is_superadmin) {
      if (project_id) {
        if (!p.inProject(Number(project_id)))
          return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
        cond.push("m.project_id=?");
        params.push(Number(project_id));
      } else if (p.project_ids?.length) {
        cond.push(
          `m.project_id IN (${p.project_ids.map(() => "?").join(",")})`
        );
        params.push(...p.project_ids);
      }
    } else if (project_id) {
      cond.push("m.project_id=?");
      params.push(Number(project_id));
    }

    if (org_id) {
      cond.push("m.org_id=?");
      params.push(Number(org_id));
    }
    if (condwg_no) {
      cond.push("m.condwg_no=?");
      params.push(condwg_no);
    }

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

// GET item (ตรวจ ABAC หลังอ่านเรคคอร์ด)
r.get("/:id", requirePerm("drawings.view"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM contract_dwg WHERE id=?", [
    id,
  ]);
  if (!row) return res.status(404).json({ error: "Not found" });
  const p = req.principal;
  if (!p.is_superadmin && !p.inProject(row.project_id))
    return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
  res.json(row);
});

// CREATE
r.post(
  "/",
  requirePerm("drawings.upload", { projectParam: "project_id" }),
  async (req, res) => {
    const {
      org_id,
      project_id,
      condwg_no,
      title,
      drawing_id,
      volume_id,
      sub_cat_id,
      sub_no,
      remark,
    } = req.body || {};
    if (!project_id || !condwg_no)
      return res
        .status(400)
        .json({ error: "project_id and condwg_no required" });
    const [rs] = await sql.query(
      `INSERT INTO contract_dwg (org_id, project_id, condwg_no, title, drawing_id, volume_id, sub_cat_id, sub_no, remark, created_by)
     VALUES (?,?,?,?,?,?,?,?,?,?)`,
      [
        org_id || null,
        project_id,
        condwg_no,
        title || null,
        drawing_id || null,
        volume_id || null,
        sub_cat_id || null,
        sub_no || null,
        remark || null,
        req.principal.user_id,
      ]
    );
    res.json({ id: rs.insertId });
  }
);

// UPDATE
r.put("/:id", requirePerm("drawings.upload"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM contract_dwg WHERE id=?", [
    id,
  ]);
  if (!row) return res.status(404).json({ error: "Not found" });
  const p = req.principal;
  if (!p.is_superadmin && !p.inProject(row.project_id))
    return res.status(403).json({ error: "FORBIDDEN_PROJECT" });

  const { title, remark } = req.body || {};
  await sql.query("UPDATE contract_dwg SET title=?, remark=? WHERE id=?", [
    title ?? row.title,
    remark ?? row.remark,
    id,
  ]);
  res.json({ ok: 1 });
});

// DELETE
r.delete("/:id", requirePerm("drawings.delete"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM contract_dwg WHERE id=?", [
    id,
  ]);
  if (!row) return res.status(404).json({ error: "Not found" });
  const p = req.principal;
  if (!p.is_superadmin && !p.inProject(row.project_id))
    return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
  await sql.query("DELETE FROM contract_dwg WHERE id=?", [id]);
  res.json({ ok: 1 });
});

export default r;
