import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/options"; import { prisma } from "@/lib/prisma"; // Helper function to check if user can manage events in a mission calendar async function canManageMissionCalendar(userId: string, calendarId: string): Promise { const calendar = await prisma.calendar.findUnique({ where: { id: calendarId }, include: { mission: { include: { missionUsers: true } } } }); // If calendar is not linked to a mission, allow (it's a regular calendar) if (!calendar?.missionId || !calendar.mission) { return true; } const mission = calendar.mission; // Check if user is the creator of the mission if (mission.creatorId === userId) { return true; } // Check if user is a gardien-temps (time guardian) for this mission const isGardienTemps = mission.missionUsers.some( (mu) => mu.userId === userId && mu.role === 'gardien-temps' ); return isGardienTemps; } export async function POST(req: NextRequest) { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { const { title, description, start, end, allDay, location, calendarId } = await req.json(); // Validation if (!title || !start || !end || !calendarId) { return NextResponse.json( { error: "Titre, début, fin et calendrier sont requis" }, { status: 400 } ); } // Verify calendar ownership const calendar = await prisma.calendar.findFirst({ where: { id: calendarId, userId: session.user.id, }, }); if (!calendar) { return NextResponse.json( { error: "Calendrier non trouvé ou non autorisé" }, { status: 404 } ); } // If calendar is linked to a mission, check permissions if (calendar.missionId) { const canManage = await canManageMissionCalendar(session.user.id, calendarId); if (!canManage) { return NextResponse.json( { error: "Seul le créateur de la mission ou le gardien-temps peut créer des événements" }, { status: 403 } ); } } // Create event with all required fields const event = await prisma.event.create({ data: { title, description: description || null, start: new Date(start), end: new Date(end), isAllDay: allDay || false, location: location || null, calendarId, userId: session.user.id, }, }); console.log("Created event:", event); 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 }); } } export async function PUT(req: NextRequest) { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } try { const data = await req.json(); console.log("Received event update data:", data); const { id, title, description, start, end, allDay, location, calendarId } = data; // Validation if (!id || !title || !start || !end || !calendarId) { console.log("Validation failed. Missing fields:", { id: !id, title: !title, start: !start, end: !end, calendarId: !calendarId }); return NextResponse.json( { error: "ID, titre, début, fin et calendrier sont requis" }, { status: 400 } ); } // Verify calendar ownership const calendar = await prisma.calendar.findFirst({ where: { id: calendarId, userId: session.user.id, }, include: { events: { where: { id } } } }); console.log("Found calendar:", calendar); if (!calendar || calendar.events.length === 0) { console.log("Calendar or event not found:", { calendarFound: !!calendar, eventsFound: calendar?.events.length }); return NextResponse.json( { error: "Événement non trouvé ou non autorisé" }, { status: 404 } ); } // If calendar is linked to a mission, check permissions if (calendar.missionId) { const canManage = await canManageMissionCalendar(session.user.id, calendarId); if (!canManage) { return NextResponse.json( { error: "Seul le créateur de la mission ou le gardien-temps peut modifier des événements" }, { status: 403 } ); } } const event = await prisma.event.update({ where: { id }, data: { title, description, start: new Date(start), end: new Date(end), isAllDay: allDay || false, location, calendarId, }, }); console.log("Updated event:", event); return NextResponse.json(event); } catch (error) { console.error("Erreur lors de la mise à jour de l'événement:", error); return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); } }