"use server";

import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { eventService } from "@/services/events/event.service";
import { Role, EventType } from "@/prisma/generated/prisma/client";
import { ValidationError, NotFoundError } 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 createEvent(data: {
  date: string;
  name: string;
  description?: string | null;
  type: string;
  room?: string | null;
  time?: string | null;
  maxPlaces?: number | null;
}) {
  try {
    await checkAdminAccess()();

    const event = await eventService.validateAndCreateEvent({
      date: data.date,
      name: data.name,
      description: data.description ?? "",
      type: data.type as EventType,
      room: data.room ?? undefined,
      time: data.time ?? undefined,
      maxPlaces: data.maxPlaces ?? undefined,
    });

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

    return { success: true, data: event };
  } catch (error) {
    console.error("Error creating event:", error);

    if (error instanceof ValidationError) {
      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 création de l'événement",
    };
  }
}

export async function updateEvent(
  eventId: string,
  data: {
    date?: string;
    name?: string;
    description?: string | null;
    type?: string;
    room?: string | null;
    time?: string | null;
    maxPlaces?: number | null;
  }
) {
  try {
    await checkAdminAccess()();

    const event = await eventService.validateAndUpdateEvent(eventId, {
      date: data.date,
      name: data.name,
      description: data.description ?? undefined,
      type: data.type as EventType,
      room: data.room ?? undefined,
      time: data.time ?? undefined,
      maxPlaces: data.maxPlaces ?? undefined,
    });

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

    return { success: true, data: event };
  } catch (error) {
    console.error("Error updating event:", 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 mise à jour de l'événement",
    };
  }
}

export async function deleteEvent(eventId: string) {
  try {
    await checkAdminAccess()();

    const existingEvent = await eventService.getEventById(eventId);

    if (!existingEvent) {
      return { success: false, error: "Événement non trouvé" };
    }

    await eventService.deleteEvent(eventId);

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

    return { success: true };
  } catch (error) {
    console.error("Error deleting event:", 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 suppression de l'événement",
    };
  }
}
