"use server";

import { revalidatePath } from "next/cache";
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";

function checkAdminAccess() {
  return async () => {
    const session = await auth();
    if (!session?.user || session.user.role !== Role.ADMIN) {
      throw new Error("Accès refusé");
    }
    return session;
  };
}

export async function updateUser(
  userId: string,
  data: {
    username?: string;
    avatar?: string | null;
    hpDelta?: number;
    xpDelta?: number;
    score?: number;
    level?: number;
    role?: string;
  }
) {
  try {
    await checkAdminAccess()();

    // Valider username si fourni
    if (data.username !== undefined) {
      try {
        await userService.validateAndUpdateUserProfile(userId, {
          username: data.username,
        });
      } catch (error) {
        if (
          error instanceof ValidationError ||
          error instanceof ConflictError
        ) {
          return { success: false, error: error.message };
        }
        throw error;
      }
    }

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

    revalidatePath("/admin");
    revalidatePath("/leaderboard");

    return { success: true, data: updatedUser };
  } catch (error) {
    console.error("Error updating user:", error);

    if (error instanceof Error && error.message === "Accès refusé") {
      return { success: false, error: "Accès refusé" };
    }

    return {
      success: false,
      error: "Erreur lors de la mise à jour de l'utilisateur",
    };
  }
}

export async function deleteUser(userId: string) {
  try {
    const session = await checkAdminAccess()();

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

    revalidatePath("/admin");
    revalidatePath("/leaderboard");

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

    if (error instanceof ValidationError) {
      return { success: false, error: error.message };
    }
    if (error instanceof NotFoundError) {
      return { success: false, error: error.message };
    }
    if (error instanceof Error && error.message === "Accès refusé") {
      return { success: false, error: "Accès refusé" };
    }

    return {
      success: false,
      error: "Erreur lors de la suppression de l'utilisateur",
    };
  }
}
