import { NextResponse } from "next/server";
import { userService } from "@/services/users/user.service";
import { ValidationError, ConflictError } from "@/services/errors";

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { email, username, password, bio, characterClass, avatar } = body;

    const user = await userService.validateAndCreateUser({
      email,
      username,
      password,
      bio,
      characterClass,
      avatar,
    });

    return NextResponse.json(
      { message: "Compte créé avec succès", userId: user.id },
      { status: 201 }
    );
  } catch (error) {
    console.error("Registration error:", error);

    if (error instanceof ValidationError || error instanceof ConflictError) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { error: "Une erreur est survenue lors de l'inscription" },
      { status: 500 }
    );
  }
}
