import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { Role, EventType } from "@/prisma/generated/prisma/client";
import { calculateEventStatus } from "@/lib/eventStatus";

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 prisma.event.findMany({
      orderBy: {
        date: "desc",
      },
      include: {
        _count: {
          select: {
            registrations: true,
          },
        },
      },
    });

    // Transformer les données pour inclure le nombre d'inscriptions
    // Le statut est calculé automatiquement en fonction de la date
    const eventsWithCount = events.map((event) => ({
      id: event.id,
      date: event.date.toISOString(),
      name: event.name,
      description: event.description,
      type: event.type,
      status: calculateEventStatus(event.date),
      room: event.room,
      time: event.time,
      maxPlaces: event.maxPlaces,
      createdAt: event.createdAt.toISOString(),
      updatedAt: event.updatedAt.toISOString(),
      registrationsCount: event._count.registrations,
    }));

    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;

    if (!date || !name || !description || !type) {
      return NextResponse.json(
        { error: "Tous les champs sont requis" },
        { status: 400 }
      );
    }

    // Convertir la date string en Date object
    const eventDate = new Date(date);
    if (isNaN(eventDate.getTime())) {
      return NextResponse.json(
        { error: "Format de date invalide" },
        { status: 400 }
      );
    }

    // Valider les enums
    if (!Object.values(EventType).includes(type)) {
      return NextResponse.json(
        { error: "Type d'événement invalide" },
        { status: 400 }
      );
    }

    const event = await prisma.event.create({
      data: {
        date: eventDate,
        name,
        description,
        type: type as EventType,
        room: room || null,
        time: time || null,
        maxPlaces: maxPlaces ? parseInt(maxPlaces) : null,
      },
    });

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