// FILE: backend/src/routes/rfa.js
// RFA: create + update-status ผ่าน stored procedures
import { Router } from "express";
import sql, { callProc } from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// CREATE (PROJECT scope) -> rfas.create
r.post(
  "/create",
  requirePerm("rfas.create", { projectParam: "project_id" }),
  async (req, res, next) => {
    try {
      const {
        project_id,
        cor_status_id,
        cor_no,
        title,
        originator_id,
        recipient_id,
        keywords = null,
        pdf_path = null,
        item_doc_ids = [],
      } = req.body || {};

      if (!project_id || !title) {
        return res.status(400).json({ error: "project_id and title required" });
      }

      const json = JSON.stringify((item_doc_ids || []).map(Number));
      await callProc("sp_rfa_create_with_items", [
        req.principal.user_id,
        project_id,
        cor_status_id ?? null,
        cor_no ?? null,
        title,
        originator_id ?? null,
        recipient_id ?? null,
        keywords,
        pdf_path,
        json,
        null,
      ]);

      res.status(201).json({ ok: true });
    } catch (e) {
      next(e);
    }
  }
);

// UPDATE STATUS (PROJECT scope) -> rfas.respond
r.post(
  "/update-status",
  requirePerm("rfas.respond"),
  async (req, res, next) => {
    try {
      const { rfa_corr_id, status_id, set_issue = 0 } = req.body || {};
      if (!rfa_corr_id || !status_id) {
        return res
          .status(400)
          .json({ error: "rfa_corr_id and status_id required" });
      }
      // enforce ABAC: find project_id of the RFA
      const [[ref]] = await sql.query(
        "SELECT project_id FROM rfas WHERE id=? LIMIT 1",
        [Number(rfa_corr_id)]
      );
      if (!ref) return res.status(404).json({ error: "RFA not found" });
      if (
        !req.principal.is_superadmin &&
        !req.principal.inProject(ref.project_id)
      ) {
        return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
      }

      await callProc("sp_rfa_update_status", [
        req.principal.user_id,
        rfa_corr_id,
        status_id,
        set_issue ? 1 : 0,
      ]);
      res.json({ ok: true });
    } catch (e) {
      next(e);
    }
  }
);

export default r;
