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

const r = Router();

// อ่านไฟล์ของแต่ละโมดูล โดยเช็ค ABAC + permission จาก principal
function readPermFor(mod) {
  switch (mod) {
    case "rfa":
      return "rfas.view";
    case "correspondence":
      return "corr.view";
    case "drawing":
      return "drawings.view";
    case "document":
      return "documents.view";
    case "transmittal":
      return "transmittals.manage"; // โมดูลนี้ seed เป็น manage
    default:
      return "documents.view";
  }
}
async function projectOf(mod, id) {
  switch (mod) {
    case "rfa": {
      const [[row]] = await sql.query(
        "SELECT project_id FROM rfas WHERE id=?",
        [id]
      );
      return row?.project_id || null;
    }
    case "correspondence": {
      const [[row]] = await sql.query(
        "SELECT project_id FROM correspondences WHERE id=?",
        [id]
      );
      return row?.project_id || null;
    }
    case "drawing": {
      const [[row]] = await sql.query(
        "SELECT project_id FROM drawings WHERE id=?",
        [id]
      );
      return row?.project_id || null;
    }
    case "document": {
      const [[row]] = await sql.query(
        "SELECT project_id FROM documents WHERE document_id=?",
        [id]
      );
      return row?.project_id || null;
    }
    case "transmittal": {
      const [[row]] = await sql.query(
        "SELECT project_id FROM transmittals WHERE id=?",
        [id]
      );
      return row?.project_id || null;
    }
    default:
      return null;
  }
}

// /:module(s)/:id/files
for (const mod of [
  "rfa",
  "correspondence",
  "drawing",
  "document",
  "transmittal",
]) {
  r.get(`/${mod}s/:id/files`, async (req, res) => {
    const ref_id = Number(req.params.id);
    const p = req.principal;
    if (!p) return res.status(401).json({ error: "Unauthenticated" });

    const need = readPermFor(mod);
    if (!(p.is_superadmin || p.permissions?.has?.(need))) {
      return res.status(403).json({ error: "FORBIDDEN", need });
    }

    const pid = await projectOf(mod, ref_id);
    if (!p.is_superadmin && (!pid || !p.inProject(pid))) {
      return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
    }

    const [rows] = await sql.query(
      `SELECT f.* FROM files f WHERE f.module=? AND f.ref_id=? ORDER BY f.file_id DESC`,
      [mod, ref_id]
    );
    res.json(rows);
  });
}

export default r;
