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

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: "asc",
      },
    });

    return NextResponse.json(events);
  } 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, status } = body;

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

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

    if (!Object.values(EventStatus).includes(status)) {
      return NextResponse.json(
        { error: "Statut d'événement invalide" },
        { status: 400 }
      );
    }

    const event = await prisma.event.create({
      data: {
        date,
        name,
        description,
        type: type as EventType,
        status: status as EventStatus,
      },
    });

    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 }
    );
  }
}

