import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { eventService } from "@/services/events/event.service";
import { Role } from "@/prisma/generated/prisma/client";
import { ValidationError } from "@/services/errors";

export async function GET() {
  try {
    const session = await auth();

    if (!session?.user || session.user.role !== Role.ADMIN) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const events = await eventService.getEventsWithStatus();

    // Transformer les données pour la sérialisation
    const eventsWithCount = events.map((event) => ({
      id: event.id,
      date: event.date.toISOString(),
      name: event.name,
      description: event.description,
      type: event.type,
      status: event.status,
      room: event.room,
      time: event.time,
      maxPlaces: event.maxPlaces,
      createdAt: event.createdAt.toISOString(),
      updatedAt: event.updatedAt.toISOString(),
      registrationsCount: event.registrationsCount,
    }));

    return NextResponse.json(eventsWithCount);
  } catch (error) {
    console.error("Error fetching events:", error);
    return NextResponse.json(
      { error: "Erreur lors de la récupération des événements" },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    const session = await auth();

    if (!session?.user || session.user.role !== Role.ADMIN) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const body = await request.json();
    const { date, name, description, type, room, time, maxPlaces } = body;

    const event = await eventService.validateAndCreateEvent({
      date,
      name,
      description,
      type,
      room,
      time,
      maxPlaces,
    });

    return NextResponse.json(event);
  } catch (error) {
    console.error("Error creating event:", error);

    if (error instanceof ValidationError) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { error: "Erreur lors de la création de l'événement" },
      { status: 500 }
    );
  }
}
