// FILE: backend/src/routes/uploads.js
// อัปโหลดไฟล์ผูกกับโมดูล (PROJECT scope): documents/drawings/correspondences/rfas/transmittals
import { Router } from "express";
import multer from "multer";
import fs from "node:fs";
import path from "node:path";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();
const UPLOAD_BASE = process.env.UPLOAD_BASE || "/share/dms-data";
const ensureDir = (p) => {
  if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
};

async function fetchRef(module, id) {
  const tbl = String(module);
  const idCol = "id";
  const [[row]] = await sql.query(
    `SELECT org_id, project_id, created_at FROM ${tbl} WHERE ${idCol}=?`,
    [Number(id)]
  );
  return row || null;
}
function sanitize(name) {
  // แทนที่อักขระไม่ปลอดภัย
  return String(name).replace(/[^A-Za-z0-9._-]+/g, "_");
}
const storage = multer.diskStorage({
  destination: async (req, _file, cb) => {
    try {
      const { module, id } = req.params;
      const ref = await fetchRef(module, id);
      if (!ref) return cb(new Error("Resource not found"));
      const dt = new Date(ref.created_at || Date.now());
      const ym = `${dt.getUTCFullYear()}-${String(
        dt.getUTCMonth() + 1
      ).padStart(2, "0")}`;
      const dir = path.join(
        UPLOAD_BASE,
        module,
        String(ref.org_id || "0"),
        String(ref.project_id || "0"),
        ym
      );
      ensureDir(dir);
      cb(null, dir);
    } catch (e) {
      cb(e);
    }
  },
  filename: (_req, file, cb) =>
    cb(null, `${Date.now()}__${sanitize(file.originalname)}`),
});
const upload = multer({ storage });

// map module -> permission
function uploadPerm(module) {
  if (module === "documents") return "documents.manage";
  if (module === "drawings") return "drawings.upload";
  if (module === "correspondences") return "corr.manage";
  if (module === "rfas") return "rfas.respond";
  if (module === "transmittals") return "transmittals.manage";
  return null;
}
async function refProjectId(module, id) {
  const [[row]] = await sql.query(
    `SELECT project_id FROM ${module} WHERE id=?`,
    [Number(id)]
  );
  return row?.project_id ?? null;
}

r.post(
  "/:module/:id/file",
  (req, res, next) => {
    const perm = uploadPerm(req.params.module);
    if (!perm) return res.status(400).json({ error: "Unsupported module" });
    return requirePerm(perm, { projectParam: undefined })(req, res, next);
  },
  async (req, res, next) => {
    // ABAC: ตรวจ project scope ของ record
    const pid = await refProjectId(req.params.module, req.params.id);
    if (
      !req.principal.is_superadmin &&
      (!pid || !req.principal.inProject(pid))
    ) {
      return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
    }
    next();
  },
  upload.single("file"),
  async (req, res) => {
    const { module, id } = req.params;
    const file = req.file;
    res.json({
      ok: 1,
      module,
      ref_id: Number(id),
      filename: file.filename,
      path: file.path,
      size: file.size,
      mime: file.mimetype,
    });
  }
);

export default r;
