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

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const body = await req.json();

  const staff = await prisma.staff.findFirst({
    where: { id, clinicId: session.id },
  });
  if (!staff) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (staff.role === "owner") {
    return NextResponse.json({ error: "Cannot modify the owner" }, { status: 403 });
  }

  const updated = await prisma.staff.update({
    where: { id },
    data: {
      ...(body.name !== undefined && { name: body.name }),
      ...(body.role !== undefined && ["doctor", "receptionist"].includes(body.role) && { role: body.role }),
      ...(body.isActive !== undefined && { isActive: body.isActive }),
    },
    select: {
      id: true, clinicId: true, name: true, email: true,
      role: true, isActive: true, createdAt: true, updatedAt: true,
    },
  });

  return NextResponse.json(updated);
}

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

  const staff = await prisma.staff.findFirst({
    where: { id, clinicId: session.id },
  });
  if (!staff) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (staff.role === "owner") {
    return NextResponse.json({ error: "Cannot delete the owner" }, { status: 403 });
  }

  await prisma.staff.delete({ where: { id } });

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