/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextResponse } from "next/server";
import { registerUser, Role } from "@/lib/auth";

// POST /api/auth/register - Public user registration
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, email, password, confirmPassword } = body;

    if (!email || !password) {
      return NextResponse.json(
        { error: "Email and password are required" },
        { status: 400 }
      );
    }

    if (password !== confirmPassword) {
      return NextResponse.json(
        { error: "Passwords do not match" },
        { status: 400 }
      );
    }

    if (password.length < 8) {
      return NextResponse.json(
        { error: "Password must be at least 8 characters long" },
        { status: 400 }
      );
    }

    const newUser = await registerUser(email, password, name, Role.ADMIN);

    return NextResponse.json(
      {
        success: true,
        message: "User registered successfully. Please sign in.",
        user: newUser,
      },
      { status: 201 }
    );
  } catch (error: any) {
    console.error("Error during registration:", error);

    if (error.message.includes("already exists")) {
      return NextResponse.json(
        { error: "Email already registered" },
        { status: 409 }
      );
    }

    return NextResponse.json({ error: error.message || "Registration failed" }, { status: 500 });
  }
}
