import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from "@/app/api/auth/options"; import { prisma } from '@/lib/prisma'; import { getPublicUrl } from '@/lib/s3'; import { S3_CONFIG } from '@/lib/s3'; // 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 list all missions (not filtered by user) export async function GET(request: Request) { try { const { authorized, userId } = await checkAuth(request); if (!authorized || !userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { searchParams } = new URL(request.url); const limit = Number(searchParams.get('limit') || '100'); // Default to 100 for "all" const offset = Number(searchParams.get('offset') || '0'); const search = searchParams.get('search'); // Build query conditions const where: any = {}; // Add search filter if provided if (search) { where.OR = [ { name: { contains: search, mode: 'insensitive' } }, { intention: { contains: search, mode: 'insensitive' } } ]; } // Get all missions with basic info (no user filtering) const missions = await prisma.mission.findMany({ where, skip: offset, take: limit, orderBy: { createdAt: 'desc' }, select: { id: true, name: true, logo: true, oddScope: true, niveau: true, missionType: true, projection: true, participation: true, services: true, intention: true, createdAt: true, creator: { select: { id: true, email: true } }, missionUsers: { select: { id: true, role: true, user: { select: { id: true, email: true } } } } } }); // Get total count const totalCount = await prisma.mission.count({ where }); // Transform logo paths to public URLs const missionsWithPublicUrls = missions.map(mission => ({ ...mission, logo: mission.logo ? `/api/missions/image/${mission.logo}` : null })); return NextResponse.json({ missions: missionsWithPublicUrls, pagination: { total: totalCount, offset, limit } }); } catch (error) { console.error('Error listing all missions:', error); return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); } }