import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from "@/app/api/auth/options"; import { prisma } from '@/lib/prisma'; import { N8nService } from '@/lib/services/n8n-service'; import { Prisma } from '@prisma/client'; // Types interface MissionCreateInput { name: string; oddScope: string[]; niveau?: string; intention?: string; missionType?: string; donneurDOrdre?: string; projection?: string; services?: string[]; participation?: string; profils?: string[]; guardians?: Record; volunteers?: string[]; creatorId?: string; logo?: { data: string; name?: string; type?: string; } | null; attachments?: Array<{ data: string; name?: string; type?: string; }>; leantimeProjectId?: string | null; outlineCollectionId?: string | null; rocketChatChannelId?: string | null; giteaRepositoryUrl?: string | null; penpotProjectId?: string | null; } interface MissionUserInput { role: string; userId: string; missionId: string; } interface MissionResponse { id: string; name: string; oddScope: string[]; niveau: string; intention: string; missionType: string; donneurDOrdre: string; projection: string; services: string[]; profils: string[]; participation: string; creatorId: string; logo: string | null; leantimeProjectId: string | null; outlineCollectionId: string | null; rocketChatChannelId: string | null; giteaRepositoryUrl: string | null; penpotProjectId: string | null; createdAt: Date; updatedAt: Date; } // Helper function to check authentication async function checkAuth(request: Request) { const session = await getServerSession(authOptions); return { authorized: !!session?.user, userId: session?.user?.id }; } // GET endpoint to list missions 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'); const name = searchParams.get('name'); const where: Prisma.MissionWhereInput = {}; if (search) { where.OR = [ { name: { contains: search, mode: 'insensitive' } }, { intention: { contains: search, mode: 'insensitive' } } ]; } if (name) { where.name = name; } const missions = await prisma.mission.findMany({ where, skip: offset, take: limit, orderBy: { createdAt: 'desc' }, include: { creator: { select: { id: true, email: true } }, missionUsers: { include: { user: { select: { id: true, email: true } } } } } }); const totalCount = await prisma.mission.count({ where }); return NextResponse.json({ missions, 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 }); } const body = await request.json(); // Simple validation if (!body.name || !body.oddScope) { return NextResponse.json({ error: 'Missing required fields', missingFields: ['name', 'oddScope'].filter(field => !body[field]) }, { status: 400 }); } // Check if this is a request from n8n const isN8nRequest = request.headers.get('x-api-key') === process.env.N8N_API_KEY; if (!isN8nRequest) { const n8nService = new N8nService(); // Simple data preparation for n8n const n8nData = { ...body, creatorId: userId, config: { N8N_API_KEY: process.env.N8N_API_KEY, MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL } }; const workflowResult = await n8nService.triggerMissionCreation(n8nData); if (!workflowResult.success) { return NextResponse.json({ error: 'Failed to create mission resources', details: workflowResult.error }, { status: 500 }); } return NextResponse.json({ success: true, message: 'Mission creation initiated', mission: body }); } // Create mission directly (n8n request) const missionData: Prisma.MissionUncheckedCreateInput = { name: body.name, oddScope: body.oddScope, niveau: body.niveau, intention: body.intention, missionType: body.missionType, donneurDOrdre: body.donneurDOrdre, projection: body.projection, services: body.services, profils: body.profils, participation: body.participation, creatorId: userId, logo: body.logo, leantimeProjectId: body.leantimeProjectId, outlineCollectionId: body.outlineCollectionId, rocketChatChannelId: body.rocketChatChannelId, giteaRepositoryUrl: body.giteaRepositoryUrl, penpotProjectId: body.penpotProjectId }; const mission = await prisma.mission.create({ data: missionData }); return NextResponse.json({ success: true, mission }); } catch (error) { console.error('Error creating mission:', error); return NextResponse.json({ error: 'Failed to create mission', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); } }