import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canUseElevatedAccess } from "@/lib/elevated-access";

export async function DELETE(_request: Request, context: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const canManagePeople = session.user.role === "owner" || canUseElevatedAccess(session.user.email);
  if (!canManagePeople) {
    return NextResponse.json({ error: "Only owners or elevated admins can delete users." }, { status: 403 });
  }

  const userId = context.params.id;
  if (!userId) {
    return NextResponse.json({ error: "User id is required." }, { status: 400 });
  }

  if (userId === session.user.id) {
    return NextResponse.json({ error: "No puedes eliminar tu propio usuario." }, { status: 400 });
  }

  const targetUser = await prisma.user.findUnique({
    where: { id: userId },
    select: {
      id: true,
      userRoles: {
        include: { role: true },
      },
    },
  });

  if (!targetUser) {
    return NextResponse.json({ error: "User not found." }, { status: 404 });
  }

  const isOwner = targetUser.userRoles.some((entry) => entry.role.key === "owner");
  if (isOwner) {
    const ownerCount = await prisma.userRole.count({
      where: {
        role: {
          key: "owner",
        },
      },
    });

    if (ownerCount <= 1) {
      return NextResponse.json({ error: "Cannot delete the last owner." }, { status: 400 });
    }
  }

  await prisma.user.delete({
    where: { id: userId },
  });

  return NextResponse.json({ ok: true });
}
