"use server";

import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { eventRegistrationService } from "@/services/events/event-registration.service";
import {
  ValidationError,
  NotFoundError,
  ConflictError,
} from "@/services/errors";

export async function registerForEvent(eventId: string) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return {
        success: false,
        error: "Vous devez être connecté pour vous inscrire",
      };
    }

    const registration = await eventRegistrationService.validateAndRegisterUser(
      session.user.id,
      eventId
    );

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

    return {
      success: true,
      message: "Inscription réussie",
      data: registration,
    };
  } catch (error) {
    console.error("Registration error:", error);

    if (error instanceof ValidationError || error instanceof ConflictError) {
      return { success: false, error: error.message };
    }
    if (error instanceof NotFoundError) {
      return { success: false, error: error.message };
    }

    return {
      success: false,
      error: "Une erreur est survenue lors de l'inscription",
    };
  }
}

export async function unregisterFromEvent(eventId: string) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return { success: false, error: "Vous devez être connecté" };
    }

    await eventRegistrationService.unregisterUserFromEvent(
      session.user.id,
      eventId
    );

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

    return { success: true, message: "Inscription annulée" };
  } catch (error) {
    console.error("Unregistration error:", error);
    return {
      success: false,
      error: "Une erreur est survenue lors de l'annulation",
    };
  }
}
