import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from "@/app/api/auth/options"; import { prisma } from '@/lib/prisma'; import { deleteMissionLogo } from '@/lib/mission-uploads'; import { getPublicUrl, S3_CONFIG } from '@/lib/s3'; import { IntegrationService } from '@/lib/services/integration-service'; // Helper function to check authentication async function checkAuth(request: Request) { const session = await getServerSession(authOptions); if (!session?.user?.id) { console.error('Unauthorized access attempt:', { url: request.url, method: request.method, headers: Object.fromEntries(request.headers) }); return { authorized: false, userId: null }; } return { authorized: true, userId: session.user.id }; } // GET endpoint to retrieve a mission by ID export async function GET(request: Request, props: { params: Promise<{ missionId: string }> }) { const params = await props.params; try { const { authorized, userId } = await checkAuth(request); if (!authorized || !userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { missionId } = params; if (!missionId) { return NextResponse.json({ error: 'Mission ID is required' }, { status: 400 }); } // Get mission with detailed info const mission = await (prisma as any).mission.findFirst({ where: { id: missionId, OR: [ { creatorId: userId }, { missionUsers: { some: { userId } } } ] }, include: { creator: { select: { id: true, email: true } }, missionUsers: { select: { id: true, role: true, user: { select: { id: true, email: true } } } }, attachments: { select: { id: true, filename: true, filePath: true, fileType: true, fileSize: true, createdAt: true }, orderBy: { createdAt: 'desc' } } } }); if (!mission) { return NextResponse.json({ error: 'Mission not found or access denied' }, { status: 404 }); } // Add public URLs to mission logo and attachments const missionWithUrls = { ...mission, logoUrl: mission.logo ? `/api/centrale/image/${mission.logo}` : null, attachments: mission.attachments.map((attachment: { id: string; filename: string; filePath: string; fileType: string; fileSize: number; createdAt: Date }) => ({ ...attachment, publicUrl: `/api/centrale/image/${attachment.filePath}` })) }; return NextResponse.json(missionWithUrls); } catch (error) { console.error('Error retrieving mission:', error); return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); } }