import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { userService } from "@/services/users/user.service";
import { userStatsService } from "@/services/users/user-stats.service";
import { Role } from "@/prisma/generated/prisma/client";
import {
  ValidationError,
  NotFoundError,
  ConflictError,
} from "@/services/errors";

export async function PUT(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth();

    if (!session?.user || session.user.role !== Role.ADMIN) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const { id } = await params;
    const body = await request.json();
    const { username, avatar, hpDelta, xpDelta, score, level, role } = body;

    // Valider username si fourni
    if (username !== undefined) {
      try {
        await userService.validateAndUpdateUserProfile(id, { username });
      } catch (error) {
        if (
          error instanceof ValidationError ||
          error instanceof ConflictError
        ) {
          return NextResponse.json({ error: error.message }, { status: 400 });
        }
        throw error;
      }
    }

    // Mettre à jour stats et profil
    const updatedUser = await userStatsService.updateUserStatsAndProfile(
      id,
      { username, avatar, hpDelta, xpDelta, score, level, role },
      {
        id: true,
        username: true,
        email: true,
        role: true,
        score: true,
        level: true,
        hp: true,
        maxHp: true,
        xp: true,
        maxXp: true,
        avatar: true,
      }
    );

    return NextResponse.json(updatedUser);
  } catch (error) {
    console.error("Error updating user:", error);
    return NextResponse.json(
      { error: "Erreur lors de la mise à jour de l'utilisateur" },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth();

    if (!session?.user || session.user.role !== Role.ADMIN) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const { id } = await params;

    await userService.validateAndDeleteUser(id, session.user.id);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error deleting user:", error);

    if (error instanceof ValidationError) {
      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 suppression de l'utilisateur" },
      { status: 500 }
    );
  }
}
