// FILE: backend/src/routes/transmittals.js
// ทั้งโมดูลใช้สิทธิ์เดียว: transmittals.manage (PROJECT)
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// LIST
r.get(
  "/",
  requirePerm("transmittals.manage", { projectParam: "project_id" }),
  async (req, res) => {
    const { project_id, tr_no, q, limit = 50, offset = 0 } = req.query;
    const P = req.principal;
    const cond = [];
    const params = [];

    if (!P.is_superadmin) {
      if (project_id) {
        const pid = Number(project_id);
        if (!P.inProject(pid))
          return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
        cond.push("t.project_id=?");
        params.push(pid);
      } else if (P.project_ids?.length) {
        cond.push(
          `t.project_id IN (${P.project_ids.map(() => "?").join(",")})`
        );
        params.push(...P.project_ids);
      }
    } else if (project_id) {
      cond.push("t.project_id=?");
      params.push(Number(project_id));
    }

    if (tr_no) {
      cond.push("t.tr_no=?");
      params.push(tr_no);
    }
    if (q) {
      cond.push("(t.tr_no LIKE ? OR t.subject LIKE ?)");
      params.push(`%${q}%`, `%${q}%`);
    }

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

// GET
r.get("/:id", requirePerm("transmittals.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM transmittals 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("transmittals.manage", { projectParam: "project_id" }),
  async (req, res) => {
    const { org_id, project_id, tr_no, subject, status } = req.body || {};
    if (!project_id || !tr_no)
      return res.status(400).json({ error: "project_id and tr_no required" });
    const [rs] = await sql.query(
      `INSERT INTO transmittals (org_id, project_id, tr_no, subject, status, created_by)
     VALUES (?,?,?,?,?,?)`,
      [
        org_id ?? null,
        project_id,
        tr_no,
        subject ?? null,
        status ?? null,
        req.principal.user_id,
      ]
    );
    res.status(201).json({ id: rs.insertId });
  }
);

// UPDATE
r.patch("/:id", requirePerm("transmittals.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM transmittals 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 allowed = ["tr_no", "subject", "status"];
  const patch = {};
  for (const k of allowed) if (k in req.body) patch[k] = req.body[k];
  if (!Object.keys(patch).length)
    return res.status(400).json({ error: "no fields to update" });

  const sets = Object.keys(patch).map((k) => `\`${k}\`=?`);
  await sql.query(`UPDATE transmittals SET ${sets.join(", ")} WHERE id=?`, [
    ...Object.values(patch),
    id,
  ]);
  res.json({ ok: 1 });
});

// DELETE
r.delete("/:id", requirePerm("transmittals.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM transmittals 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 transmittals WHERE id=?", [id]);
  res.json({ ok: 1 });
});

export default r;
