// pages/api/users/[id].js
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";

/**
 * Auth: Authorization: Bearer <NEXT_PUBLIC_SECRET_TOKEN>
 */

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" });
  }

  try {
    // EDIT
    if (req.method === "PUT" || req.method === "PATCH") {
      const { name, pass, role } = req.body || {};

      const data = {};
      if (name !== undefined) data.name = String(name).trim();
      if (role !== undefined) data.role = Number(role);

      // ✅ hash password only if provided and not empty
      if (pass !== undefined && String(pass).trim().length > 0) {
        data.pass = await bcrypt.hash(String(pass), 10);
      }

      if (Object.keys(data).length === 0) {
        return res
          .status(400)
          .json({ success: false, message: "No fields to update" });
      }

      const user = await prisma.user.update({
        where: { id },
        data,
        select: { id: true, name: true, role: true, createdAt: true, updatedAt: true },
      });

      return res.status(200).json({ success: true, user });
    }

    // DELETE
    if (req.method === "DELETE") {
      await prisma.user.delete({ where: { id } });
      return res.status(200).json({ success: true });
    }

    // READ
    if (req.method === "GET") {
      const user = await prisma.user.findUnique({
        where: { id },
        select: { id: true, name: true, role: true, createdAt: true, updatedAt: true },
      });
      if (!user) {
        return res.status(404).json({ success: false, message: "Not Found" });
      }
      return res.status(200).json({ success: true, user });
    }

    return res.status(405).json({ success: false, message: "Method Not Allowed" });
  } catch (err) {
    if (err?.code === "P2025") {
      return res.status(404).json({ success: false, message: "Not Found" });
    }
    console.error(err);
    return res.status(500).json({ success: false, message: "Server Error" });
  }
}