import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/options"; import { prisma } from "@/lib/prisma"; import { logger } from "@/lib/logger"; /** * Handles GET requests to retrieve a calendar by its ID. * * @param req - The incoming request object. * @param params - An object containing the route parameters. * @param params.id - The ID of the calendar to retrieve. * @returns A JSON response containing the calendar data if found and authorized, * or an error message with the appropriate HTTP status code. * * - 401: If the user is not authenticated. * - 403: If the user is not authorized to access the calendar. * - 404: If the calendar is not found. * - 500: If there is a server error during the retrieval process. */ export async function GET( req: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const session = await getServerSession(authOptions); if (!session?.user?.username) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { const { id } = await params; const calendar = await prisma.calendar.findUnique({ where: { id: id, }, }); if (!calendar) { return NextResponse.json( { error: "Calendrier non trouvé" }, { status: 404 } ); } // Vérification que l'utilisateur est bien le propriétaire if (calendar.userId !== session.user.username) { return NextResponse.json({ error: "Non autorisé" }, { status: 403 }); } return NextResponse.json(calendar); } catch (error) { console.error("Erreur lors de la récupération du calendrier:", error); return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); } } /** * Handles the PUT request to update a calendar. * * @param req - The incoming request object. * @param params - An object containing the route parameters. * @param params.id - The ID of the calendar to update. * @returns A JSON response with the updated calendar data or an error message. * * @throws {401} If the user is not authenticated. * @throws {404} If the calendar is not found. * @throws {403} If the user is not authorized to update the calendar. * @throws {400} If the calendar name is not provided. * @throws {500} If there is a server error during the update process. */ export async function PUT( req: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const session = await getServerSession(authOptions); if (!session?.user?.username) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { const { id } = await params; // Vérifier que le calendrier existe et appartient à l'utilisateur const existingCalendar = await prisma.calendar.findUnique({ where: { id: id, }, }); if (!existingCalendar) { return NextResponse.json( { error: "Calendrier non trouvé" }, { status: 404 } ); } if (existingCalendar.userId !== session.user.username) { return NextResponse.json({ error: "Non autorisé" }, { status: 403 }); } const { name, color, description } = await req.json(); // Validation if (!name) { return NextResponse.json( { error: "Le nom du calendrier est requis" }, { status: 400 } ); } const updatedCalendar = await prisma.calendar.update({ where: { id: id, }, data: { name, color, description, }, }); return NextResponse.json(updatedCalendar); } catch (error) { console.error("Erreur lors de la mise à jour du calendrier:", error); return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); } } /** * Handles the DELETE request to remove a calendar by its ID. * * @param req - The incoming Next.js request object. * @param params - An object containing the route parameters. * @param params.id - The ID of the calendar to be deleted. * @returns A JSON response indicating the result of the deletion operation. * * - If the user is not authenticated, returns a 401 status with an error message. * - If the calendar does not exist, returns a 404 status with an error message. * - If the calendar does not belong to the authenticated user, returns a 403 status with an error message. * - If the calendar is successfully deleted, returns a 204 status with no content. * - If an error occurs during the deletion process, returns a 500 status with an error message. */ export async function DELETE( req: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { const { id } = await params; const calendar = await prisma.calendar.findUnique({ where: { id }, include: { mission: true, }, }); if (!calendar) { return NextResponse.json( { error: "Calendrier non trouvé" }, { status: 404 } ); } // Check permissions // Allow deletion if: // 1. User owns the calendar // 2. OR it's a group calendar (starts with "Groupe:") // 3. OR user created the associated mission const isOwner = calendar.userId === session.user.id; const isGroupCalendar = calendar.name.startsWith("Groupe:"); const isMissionCreator = calendar.mission && calendar.mission.creatorId === session.user.id; if (!isOwner && !isGroupCalendar && !isMissionCreator) { return NextResponse.json( { error: "Vous n'avez pas la permission de supprimer ce calendrier" }, { status: 403 } ); } // For group calendars, log the deletion if (isGroupCalendar) { logger.info('Deleting group calendar', { calendarId: id, calendarName: calendar.name, userId: session.user.id }); } // Delete the calendar (cascade will delete events) await prisma.calendar.delete({ where: { id }, }); logger.info('Calendar deleted successfully', { calendarId: id, calendarName: calendar.name }); return NextResponse.json({ success: true, message: "Calendrier supprimé avec succès" }); } catch (error) { logger.error('Error deleting calendar', { error }); console.error("Erreur lors de la suppression du calendrier:", error); return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); } }