// FILE: backend/src/routes/documents.js
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 {
      q,
      project_id,
      status,
      category,
      page = 1,
      page_size = 20,
    } = req.query;
    const limit = Math.min(Number(page_size) || 20, 100);
    const offset = (Math.max(Number(page) || 1, 1) - 1) * limit;

    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 (status) {
      cond.push("d.status=?");
      params.push(status);
    }
    if (category) {
      cond.push("d.category=?");
      params.push(category);
    }
    if (q) {
      cond.push("(LOWER(d.title) LIKE ? OR d.doc_no LIKE ?)");
      params.push(`%${String(q).toLowerCase()}%`, `%${q}%`);
    }

    const where = cond.length ? `WHERE ${cond.join(" AND ")}` : "";
    const [[{ cnt }]] = await sql.query(
      `SELECT COUNT(*) AS cnt FROM documents d ${where}`,
      params
    );
    const [rows] = await sql.query(
      `SELECT d.* FROM documents d ${where} ORDER BY d.created_at DESC LIMIT ? OFFSET ?`,
      [...params, limit, offset]
    );
    res.json({ items: rows, total: cnt, page: Number(page), page_size: limit });
  }
);

// GET
r.get("/:id", requirePerm("documents.view"), async (req, res) => {
  const id = Number(req.params.id);
  const [[row]] = await sql.query(
    "SELECT * FROM documents WHERE document_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 { project_id, doc_no, title, category, 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 documents (project_id, doc_no, title, category, status, created_by)
     VALUES (?,?,?,?,?,?)`,
      [
        project_id,
        doc_no,
        title || null,
        category || null,
        status || null,
        req.principal.user_id,
      ]
    );
    res.status(201).json({ document_id: rs.insertId });
  }
);

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

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

export default r;
