// FILE: backend/src/routes/volumes.js
// Master data: volumes
// - Read:  organizations.view (GLOBAL)
// - Write: settings.manage     (GLOBAL)

import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();

// LIST
r.get("/", requirePerm("organizations.view"), async (_req, res) => {
  const [rows] = await sql.query(
    "SELECT volume_id, volume_code, volume_name FROM volumes ORDER BY volume_code ASC"
  );
  res.json(rows);
});

// CREATE
r.post("/", requirePerm("settings.manage"), async (req, res) => {
  const { volume_code, volume_name } = req.body || {};
  if (!volume_code || !volume_name) {
    return res
      .status(400)
      .json({ error: "volume_code and volume_name required" });
  }
  const [rs] = await sql.query(
    "INSERT INTO volumes (volume_code, volume_name) VALUES (?, ?)",
    [volume_code, volume_name]
  );
  res.status(201).json({ volume_id: rs.insertId });
});

// UPDATE
r.put("/:id", requirePerm("settings.manage"), async (req, res) => {
  const id = Number(req.params.id);
  const { volume_name } = req.body || {};
  if (!volume_name)
    return res.status(400).json({ error: "volume_name required" });
  await sql.query("UPDATE volumes SET volume_name=? WHERE volume_id=?", [
    volume_name,
    id,
  ]);
  res.json({ ok: true });
});

// DELETE
r.delete("/:id", requirePerm("settings.manage"), async (req, res) => {
  const id = Number(req.params.id);
  await sql.query("DELETE FROM volumes WHERE volume_id=?", [id]);
  res.json({ ok: true });
});

export default r;
