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

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

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

    const { id: eventId } = await params;

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

    return NextResponse.json(
      { message: "Inscription réussie", registration },
      { status: 201 }
    );
  } catch (error) {
    console.error("Registration error:", error);
    
    if (
      error instanceof ValidationError ||
      error instanceof ConflictError
    ) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }
    if (error instanceof NotFoundError) {
      return NextResponse.json({ error: error.message }, { status: 404 });
    }
    
    return NextResponse.json(
      { error: "Une erreur est survenue lors de l'inscription" },
      { status: 500 }
    );
  }
}

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

    if (!session?.user?.id) {
      return NextResponse.json(
        { error: "Vous devez être connecté" },
        { status: 401 }
      );
    }

    const { id: eventId } = await params;

    // Supprimer l'inscription
    await eventRegistrationService.unregisterUserFromEvent(
      session.user.id,
      eventId
    );

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

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

    if (!session?.user?.id) {
      return NextResponse.json({ registered: false });
    }

    const { id: eventId } = await params;

    const isRegistered = await eventRegistrationService.checkUserRegistration(
      session.user.id,
      eventId
    );

    return NextResponse.json({ registered: isRegistered });
  } catch (error) {
    console.error("Check registration error:", error);
    return NextResponse.json({ registered: false });
  }
}
