import { NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { canManageTournament } from "@/lib/permissions"; export async function POST( request: Request, { params }: { params: { id: string } } ) { try { const tournamentId = parseInt(params.id, 10); if (isNaN(tournamentId)) { return NextResponse.json( { error: "Invalid tournament ID" }, { status: 400 } ); } const body = await request.json(); const { playerIds } = body; if (!playerIds || !Array.isArray(playerIds)) { return NextResponse.json( { error: "playerIds array is required" }, { status: 400 } ); } // Check permissions const permission = await canManageTournament(tournamentId); if (!permission.allowed) { return NextResponse.json( { error: permission.reason || 'Insufficient permissions' }, { status: 403 } ); } // Add participants to tournament const participants = await Promise.all( playerIds.map(async (playerId: number) => { try { // Check if participant already exists const existing = await prisma.eventParticipant.findFirst({ where: { eventId: tournamentId, playerId: playerId, }, }); if (existing) { return existing; } // Create new participant return await prisma.eventParticipant.create({ data: { eventId: tournamentId, playerId: playerId, status: "registered", registrationDate: new Date(), }, }); } catch (error) { console.error(`Failed to add participant ${playerId}:`, error); return null; } }) ); const successfulParticipants = participants.filter(p => p !== null); return NextResponse.json({ success: true, added: successfulParticipants.length, participants: successfulParticipants, }); } catch (error) { console.error("Failed to add participants:", error); return NextResponse.json( { error: "Failed to add participants" }, { status: 500 } ); } }