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

export async function GET() {
  try {
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    const user = await userService.getUserById(session.user.id, {
      id: true,
      email: true,
      username: true,
      avatar: true,
      bio: true,
      characterClass: true,
      hp: true,
      maxHp: true,
      xp: true,
      maxXp: true,
      level: true,
      score: true,
      createdAt: true,
    });

    if (!user) {
      return NextResponse.json(
        { error: "Utilisateur non trouvé" },
        { status: 404 }
      );
    }

    return NextResponse.json(user);
  } catch (error) {
    console.error("Error fetching profile:", error);
    return NextResponse.json(
      { error: "Erreur lors de la récupération du profil" },
      { status: 500 }
    );
  }
}

export async function PUT(request: Request) {
  try {
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    const body = await request.json();
    const { username, avatar, bio, characterClass } = body;

    const updatedUser = await userService.validateAndUpdateUserProfile(
      session.user.id,
      { username, avatar, bio, characterClass },
      {
        id: true,
        email: true,
        username: true,
        avatar: true,
        bio: true,
        characterClass: true,
        hp: true,
        maxHp: true,
        xp: true,
        maxXp: true,
        level: true,
        score: true,
      }
    );

    return NextResponse.json(updatedUser);
  } catch (error) {
    console.error("Error updating profile:", error);

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

    return NextResponse.json(
      { error: "Erreur lors de la mise à jour du profil" },
      { status: 500 }
    );
  }
}
