// FILE: backend/src/routes/views.js
// จำกัดเฉพาะแอดมินระบบ: settings.manage
import { Router } from "express";
import sql from "../db/index.js";
import { requirePerm } from "../middleware/requirePerm.js";

const r = Router();
const DB_NAME = process.env.DB_NAME || "dms_db";

r.get("/", requirePerm("settings.manage"), async (_req, res) => {
  const [rows] = await sql.query(
    `SELECT TABLE_SCHEMA AS db, TABLE_NAME AS view_name
       FROM information_schema.VIEWS
      WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME`,
    [DB_NAME]
  );
  res.json(rows);
});

r.get("/:view_name", requirePerm("settings.manage"), async (req, res) => {
  const viewName = req.params.view_name;
  const [[row]] = await sql.query(
    `SELECT VIEW_DEFINITION AS definition
       FROM information_schema.VIEWS
      WHERE TABLE_SCHEMA=? AND TABLE_NAME=?`,
    [DB_NAME, viewName]
  );
  if (!row) return res.status(404).json({ error: "Not found" });
  res.json({ view: viewName, definition: row.definition });
});

export default r;
