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

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

    if (!userId) {
      return NextResponse.json(
        { error: "ID utilisateur requis" },
        { status: 400 }
      );
    }

    const updatedUser = await userService.validateAndCompleteRegistration(
      userId,
      { username, avatar, bio, characterClass }
    );

    return NextResponse.json({
      message: "Profil finalisé avec succès",
      userId: updatedUser.id,
    });
  } catch (error) {
    console.error("Error completing registration:", error);
    
    if (
      error instanceof ValidationError ||
      error instanceof ConflictError
    ) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }
    if (error instanceof NotFoundError) {
      return NextResponse.json({ error: error.message }, { status: 404 });
    }
    
    return NextResponse.json(
      {
        error: `Erreur lors de la finalisation de l'inscription: ${error instanceof Error ? error.message : "Erreur inconnue"}`,
      },
      { status: 500 }
    );
  }
}
