import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const establishmentId = searchParams.get("establishmentId");
  const role = searchParams.get("role");

  const where: any = {};
  if (establishmentId) where.establishmentId = establishmentId;
  if (role) where.role = role;

  const users = await prisma.user.findMany({
    where,
    orderBy: { createdAt: "desc" },
  });
  return NextResponse.json(users);
}

export async function POST(req: NextRequest) {
  const body = await req.json();
  const { email, password, role, establishmentId } = body;
  const user = await prisma.user.create({
    data: {
      email,
      password: await hashPassword(password),
      role,
      establishmentId,
    },
  });
  return NextResponse.json(user, { status: 201 });
}

export async function DELETE(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const id = searchParams.get("id");
  if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
  await prisma.user.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}
