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

export async function GET() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const staff = await prisma.staff.findMany({
    where: { clinicId: session.id },
    orderBy: { createdAt: "desc" },
    select: {
      id: true, clinicId: true, name: true, email: true,
      role: true, isActive: true, createdAt: true, updatedAt: true,
    },
  });

  return NextResponse.json(staff);
}

export async function POST(req: Request) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json();
  const { name, email, password, role } = body;

  if (!name || !email || !password) {
    return NextResponse.json({ error: "Name, email, and password are required" }, { status: 400 });
  }

  if (role && !["doctor", "receptionist"].includes(role)) {
    return NextResponse.json({ error: "Invalid role" }, { status: 400 });
  }

  const existing = await prisma.staff.findUnique({
    where: { clinicId_email: { clinicId: session.id, email } },
  });
  if (existing) {
    return NextResponse.json({ error: "A staff member with this email already exists" }, { status: 409 });
  }

  const passwordHash = await bcrypt.hash(password, 10);

  const staff = await prisma.staff.create({
    data: {
      clinicId: session.id,
      name,
      email,
      passwordHash,
      role: role || "receptionist",
    },
    select: {
      id: true, clinicId: true, name: true, email: true,
      role: true, isActive: true, createdAt: true, updatedAt: true,
    },
  });

  return NextResponse.json(staff);
}
