// pages/api/users/index.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;

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

      if (!name || !pass || role === undefined) {
        return res
          .status(400)
          .json({ success: false, message: "name, pass, role are required" });
      }

      // ✅ hash password
      const saltRounds = 10;
      const hashedPass = await bcrypt.hash(String(pass), saltRounds);

      const user = await prisma.user.create({
        data: {
          name: String(name).trim(),
          pass: hashedPass,
          role: Number(role),
        },
        select: { id: true, name: true, role: true, createdAt: true, updatedAt: true },
      });

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

    // LIST
    if (req.method === "GET") {
      const users = await prisma.user.findMany({
        orderBy: { id: "desc" },
        select: { id: true, name: true, role: true, createdAt: true, updatedAt: true },
      });
      return res.status(200).json({ success: true, users });
    }

    return res.status(405).json({ success: false, message: "Method Not Allowed" });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ success: false, message: "Server Error" });
  }
}