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'; 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 list missions with filters 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') || '10'); 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 missions with basic info const missions = await (prisma as any).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 as any).mission.count({ where }); // Transform logo paths to public URLs const missionsWithPublicUrls = missions.map((mission: any) => ({ ...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 missions:', error); return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); } } // POST endpoint to create a new mission export async function POST(request: Request) { try { const { authorized, userId } = await checkAuth(request); if (!authorized || !userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // Parse the request body const body = await request.json(); const { name, logo, oddScope, niveau, intention, missionType, donneurDOrdre, projection, services, participation, profils, guardians, volunteers } = body; // Validate required fields if (!name || !niveau || !intention || !missionType || !donneurDOrdre || !projection) { return NextResponse.json({ error: 'Missing required fields', required: { name: true, niveau: true, intention: true, missionType: true, donneurDOrdre: true, projection: true }, received: { name: !!name, niveau: !!niveau, intention: !!intention, missionType: !!missionType, donneurDOrdre: !!donneurDOrdre, projection: !!projection } }, { status: 400 }); } // Wrap the mission creation and integration in a transaction const result = await prisma.$transaction(async (tx: any) => { // Create the mission const mission = await tx.mission.create({ data: { name, logo, oddScope: oddScope || [], niveau, intention, missionType, donneurDOrdre, projection, services: services || [], participation, profils: profils || [], creatorId: userId } }); // Add guardians if provided if (guardians) { const guardianRoles = ['gardien-temps', 'gardien-parole', 'gardien-memoire']; const guardianEntries = Object.entries(guardians) .filter(([role, userId]) => guardianRoles.includes(role) && userId) .map(([role, userId]) => ({ role, userId: userId as string, missionId: mission.id })); if (guardianEntries.length > 0) { await tx.missionUser.createMany({ data: guardianEntries }); } } // Add volunteers if provided if (volunteers && volunteers.length > 0) { const volunteerEntries = volunteers.map((userId: string) => ({ role: 'volontaire', userId, missionId: mission.id })); await tx.missionUser.createMany({ data: volunteerEntries }); } return mission; }); try { // Initialize external integrations after transaction completes const integrationService = new IntegrationService(); const integrationResult = await integrationService.setupIntegrationsForMission(result.id); if (!integrationResult.success) { // If integration failed, the mission was already deleted in the integration service return NextResponse.json({ error: 'Failed to set up external services', details: integrationResult.error }, { status: 500 }); } return NextResponse.json({ success: true, mission: { id: result.id, name: result.name, createdAt: result.createdAt }, integrations: { status: 'success', data: integrationResult.data } }); } catch (integrationError) { // If there's any unhandled error, delete the mission and report failure console.error('Integration error:', integrationError); await (prisma as any).mission.delete({ where: { id: result.id } }); return NextResponse.json({ error: 'Failed to set up external services', details: integrationError instanceof Error ? integrationError.message : String(integrationError) }, { status: 500 }); } } catch (error) { console.error('Error creating mission:', error); return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); } }