// pages/api/policies/[id].js
import prisma from "@/lib/prisma";

function assertAuth(req, res) {
  const secret = process.env.NEXT_PUBLIC_SECRET_TOKEN;
  const header = req.headers.authorization || "";
  if (!secret || header !== `Bearer ${secret}`) {
    res.status(401).json({ success: false, message: "Unauthorized" });
    return false;
  }
  return true;
}

export default async function handler(req, res) {
  if (!assertAuth(req, res)) return;

  const id = Number(req.query.id);
  if (!Number.isFinite(id)) {
    return res.status(400).json({ success: false, message: "Invalid id" });
  }

  if (req.method !== "GET") {
    return res.status(405).json({ success: false, message: "Method Not Allowed" });
  }

  try {
    const policy = await prisma.policy.findUnique({ where: { id } });
    if (!policy) return res.status(404).json({ success: false, message: "Not Found" });
    return res.status(200).json({ success: true, policy });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ success: false, message: "Server Error" });
  }
}