import { NextRequest, NextResponse } from "next/server";
import { requireSuperAdminAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import bcrypt from "bcryptjs";
import validator from "validator";

export async function POST(request: NextRequest) {
  try {
    const currentUser = await requireSuperAdminAuth();
    if (!currentUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

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

    // Validate required fields
    if (!name || !email || !username || !password || !role) {
      return NextResponse.json(
        { error: "All fields required" },
        { status: 400 },
      );
    }

    // Validate email
    if (!validator.isEmail(email)) {
      return NextResponse.json({ error: "Invalid email" }, { status: 400 });
    }

    // Validate role
    if (!["STAFF", "ADMIN", "SUPER_ADMIN"].includes(role)) {
      return NextResponse.json({ error: "Invalid role" }, { status: 400 });
    }

    // Validate password strength (min 12 characters)
    if (password.length < 12) {
      return NextResponse.json(
        { error: "Password must be at least 12 characters" },
        { status: 400 },
      );
    }

    // Check if username or email already exists
    const existing = await prisma.users.findFirst({
      where: {
        OR: [{ email }, { username }],
      },
    });

    if (existing) {
      return NextResponse.json(
        { error: "Username or email already exists" },
        { status: 409 },
      );
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 12);

    // Create staff user
    const newStaff = await prisma.users.create({
      data: {
        name,
        email,
        username,
        password: hashedPassword,
        role,
        emailVerified: new Date(),
        isActive: true,
      },
    });

    // Log staff creation

    return NextResponse.json({
      success: true,
      staff: {
        id: newStaff.id,
        name: newStaff.name,
        email: newStaff.email,
        username: newStaff.username,
        role: newStaff.role,
      },
    });
  } catch (error) {
    console.error("Failed to create staff member:", error);
    return NextResponse.json(
      { error: "Failed to create staff member" },
      { status: 500 },
    );
  }
}
