"use server";

import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { sitePreferencesService } from "@/services/preferences/site-preferences.service";
import { Role } from "@/prisma/generated/prisma/client";

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 updateSitePreferences(data: {
  homeBackground?: string | null;
  eventsBackground?: string | null;
  leaderboardBackground?: string | null;
  challengesBackground?: string | null;
  eventRegistrationPoints?: number;
  eventFeedbackPoints?: number;
  houseJoinPoints?: number;
  houseLeavePoints?: number;
  houseCreatePoints?: number;
}) {
  try {
    await checkAdminAccess()();

    const preferences = await sitePreferencesService.updateSitePreferences({
      homeBackground: data.homeBackground,
      eventsBackground: data.eventsBackground,
      leaderboardBackground: data.leaderboardBackground,
      challengesBackground: data.challengesBackground,
      eventRegistrationPoints: data.eventRegistrationPoints,
      eventFeedbackPoints: data.eventFeedbackPoints,
      houseJoinPoints: data.houseJoinPoints,
      houseLeavePoints: data.houseLeavePoints,
      houseCreatePoints: data.houseCreatePoints,
    });

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

    return { success: true, data: preferences };
  } catch (error) {
    console.error("Error updating admin preferences:", 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 des préférences",
    };
  }
}
