// FILE: backend/src/routes/technicaldocs.js
// แมปเป็นเอกสารประเภทหนึ่ง → ใช้สิทธิ์ documents.view/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("documents.view", { projectParam: "project_id" }),
  async (req, res) => {
    const { project_id, status, 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 (status) {
      cond.push("t.status=?");
      params.push(status);
    }
    if (q) {
      cond.push("(t.doc_no LIKE ? OR t.title LIKE ?)");
      params.push(`%${q}%`, `%${q}%`);
    }

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

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

// UPDATE
r.put("/:id", requirePerm("documents.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM technicaldocs 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, status } = req.body || {};
  await sql.query("UPDATE technicaldocs SET title=?, status=? WHERE id=?", [
    title ?? row.title,
    status ?? row.status,
    id,
  ]);
  res.json({ ok: 1 });
});

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

export default r;
