import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { prisma } from "@/lib/prisma"; /** * Handles the GET request to retrieve events for a specific calendar. * * @param req - The incoming request object. * @param params - An object containing the route parameters. * @param params.id - The ID of the calendar. * @returns A JSON response containing the events or an error message. * * The function performs the following steps: * 1. Retrieves the server session to check if the user is authenticated. * 2. Verifies that the calendar exists and belongs to the authenticated user. * 3. Retrieves and filters events based on optional date parameters (`start` and `end`). * 4. Returns the filtered events in ascending order of their start date. * * Possible response statuses: * - 200: Successfully retrieved events. * - 401: User is not authenticated. * - 403: User is not authorized to access the calendar. * - 404: Calendar not found. * - 500: Server error occurred while retrieving events. */ export async function GET( req: NextRequest, { params }: { params: { id: string } } ) { const session = await getServerSession(authOptions); if (!session?.user?.username) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { // Vérifier que le calendrier appartient à l'utilisateur const calendar = await prisma.calendar.findUnique({ where: { id: params.id, }, }); if (!calendar) { return NextResponse.json( { error: "Calendrier non trouvé" }, { status: 404 } ); } if (calendar.userId !== session.user.username) { return NextResponse.json({ error: "Non autorisé" }, { status: 403 }); } // Récupérer les paramètres de filtrage de date s'ils existent const { searchParams } = new URL(req.url); const startParam = searchParams.get("start"); const endParam = searchParams.get("end"); let whereClause: any = { calendarId: params.id, }; if (startParam && endParam) { whereClause.AND = [ { start: { lte: new Date(endParam), }, }, { end: { gte: new Date(startParam), }, }, ]; } const events = await prisma.event.findMany({ where: whereClause, orderBy: { start: "asc", }, }); return NextResponse.json(events); } catch (error) { console.error("Erreur lors de la récupération des événements:", error); return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); } } /** * Handles the creation of a new event for a specific calendar. * * @param req - The incoming request object. * @param params - An object containing the route parameters. * @param params.id - The ID of the calendar to which the event will be added. * @returns A JSON response with the created event data or an error message. * * @throws {401} If the user is not authenticated. * @throws {404} If the specified calendar is not found. * @throws {403} If the user is not authorized to add events to the specified calendar. * @throws {400} If the required fields (title, start, end) are missing. * @throws {500} If there is a server error during event creation. */ export async function POST( req: NextRequest, { params }: { params: { id: string } } ) { const session = await getServerSession(authOptions); if (!session?.user?.username) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { const calendar = await prisma.calendar.findUnique({ where: { id: params.id, }, }); if (!calendar) { return NextResponse.json( { error: "Calendrier non trouvé" }, { status: 404 } ); } if (calendar.userId !== session.user.username) { return NextResponse.json({ error: "Non autorisé" }, { status: 403 }); } const { title, description, start, end, location, isAllDay } = await req.json(); // Validation if (!title) { return NextResponse.json( { error: "Le titre est requis" }, { status: 400 } ); } if (!start || !end) { return NextResponse.json( { error: "Les dates de début et de fin sont requises" }, { status: 400 } ); } const event = await prisma.event.create({ data: { title, description, start: new Date(start), end: new Date(end), location, isAllDay: isAllDay || false, calendarId: params.id, }, }); return NextResponse.json(event, { status: 201 }); } catch (error) { console.error("Erreur lors de la création de l'événement:", error); return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); } }