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

const r = Router();

// LIST
r.get(
  "/",
  requirePerm("drawings.view", { projectParam: "project_id" }),
  async (req, res) => {
    const { project_id, org_id, code, q, limit = 50, offset = 0 } = req.query;
    const p = req.principal;
    const params = [];
    const cond = [];

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

    if (org_id) {
      cond.push("d.org_id=?");
      params.push(Number(org_id));
    }
    if (code) {
      cond.push("d.dwg_code=?");
      params.push(code);
    }
    if (q) {
      cond.push("(d.dwg_no LIKE ? OR d.title LIKE ?)");
      params.push(`%${q}%`, `%${q}%`);
    }

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

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

// UPDATE  (ใช้สิทธิ์ drawings.upload)
r.put("/:id", requirePerm("drawings.upload"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query("SELECT * FROM drawings 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 } = req.body || {};
  await sql.query("UPDATE drawings SET title=? WHERE id=?", [
    title ?? row.title,
    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 drawings 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 drawings WHERE id=?", [id]);
  res.json({ ok: 1 });
});

export default r;
