import { NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { calculateTeamElo, calculateTeamEloChange } from "@/lib/elo-utils"; import { getSession } from "@/lib/auth-simple"; interface MatchInput { eventId?: number; round?: number; table?: string; team1P1Name: string; team1P2Name: string; team2P1Name: string; team2P2Name: string; team1Score: number; team2Score: number; isCasual?: boolean; } /** * POST /api/matches/bulk * * Create multiple matches in bulk */ export async function POST(request: Request) { try { const body = await request.json(); const { matches } = body; if (!Array.isArray(matches) || matches.length === 0) { return NextResponse.json( { error: "matches array is required and must not be empty" }, { status: 400 } ); } // Validate each match const errors: string[] = []; const validMatches: MatchInput[] = []; for (let i = 0; i < matches.length; i++) { const match = matches[i]; const matchNum = i + 1; if (!match.team1P1Name || !match.team1P2Name || !match.team2P1Name || !match.team2P2Name) { errors.push(`Match ${matchNum}: All player names are required`); continue; } if (typeof match.team1Score !== "number" || typeof match.team2Score !== "number") { errors.push(`Match ${matchNum}: Scores must be numbers`); continue; } if (match.team1Score < 0 || match.team2Score < 0) { errors.push(`Match ${matchNum}: Scores cannot be negative`); continue; } if (match.team1Score === match.team2Score && match.isCasual) { // Allow ties in casual matches } validMatches.push(match); } const importedMatches: any[] = []; // Process each valid match for (const match of validMatches) { try { // Find or create players const player1Name = match.team1P1Name.trim(); const player2Name = match.team1P2Name.trim(); const player3Name = match.team2P1Name.trim(); const player4Name = match.team2P2Name.trim(); const player1 = await findOrCreatePlayer(player1Name); const player2 = await findOrCreatePlayer(player2Name); const player3 = await findOrCreatePlayer(player3Name); const player4 = await findOrCreatePlayer(player4Name); // Check if this is a casual match or tournament match const isCasual = match.isCasual || !match.eventId; // Calculate ELO changes const player1Rating = player1.currentElo; const player2Rating = player2.currentElo; const player3Rating = player3.currentElo; const player4Rating = player4.currentElo; const team1Rating = calculateTeamElo(player1Rating, player2Rating); const team2Rating = calculateTeamElo(player3Rating, player4Rating); const team1ScoreNormalized = match.team1Score > match.team2Score ? 1 : match.team1Score === match.team2Score ? 0.5 : 0; const team1Change = calculateTeamEloChange(team1Rating, team2Rating, team1ScoreNormalized); const team2Change = -team1Change; const p1Change = Math.round(team1Change / 2); const p2Change = Math.round(team1Change / 2); const p3Change = Math.round(team2Change / 2); const p4Change = Math.round(team2Change / 2); // Create the match const matchData: any = { team1P1Id: player1.id, team1P2Id: player2.id, team2P1Id: player3.id, team2P2Id: player4.id, team1Score: match.team1Score, team2Score: match.team2Score, playedAt: new Date(), isCasual, }; if (match.eventId) { matchData.eventId = match.eventId; } const createdMatch = await prisma.match.create({ data: matchData, include: { player1P1: true, player1P2: true, player2P1: true, player2P2: true, }, }); // Update player stats await prisma.player.update({ where: { id: player1.id }, data: { currentElo: player1.currentElo + p1Change, gamesPlayed: { increment: 1 }, wins: match.team1Score > match.team2Score ? { increment: 1 } : undefined, losses: match.team1Score < match.team2Score ? { increment: 1 } : undefined, }, }); await prisma.player.update({ where: { id: player2.id }, data: { currentElo: player2.currentElo + p2Change, gamesPlayed: { increment: 1 }, wins: match.team1Score > match.team2Score ? { increment: 1 } : undefined, losses: match.team1Score < match.team2Score ? { increment: 1 } : undefined, }, }); await prisma.player.update({ where: { id: player3.id }, data: { currentElo: player3.currentElo + p3Change, gamesPlayed: { increment: 1 }, wins: match.team2Score > match.team1Score ? { increment: 1 } : undefined, losses: match.team2Score < match.team1Score ? { increment: 1 } : undefined, }, }); await prisma.player.update({ where: { id: player4.id }, data: { currentElo: player4.currentElo + p4Change, gamesPlayed: { increment: 1 }, wins: match.team2Score > match.team1Score ? { increment: 1 } : undefined, losses: match.team2Score < match.team1Score ? { increment: 1 } : undefined, }, }); // Create Elo snapshots await prisma.eloSnapshot.createMany({ data: [ { playerId: player1.id, matchId: createdMatch.id, ratingBefore: player1Rating, ratingAfter: player1Rating + p1Change, ratingChange: p1Change }, { playerId: player2.id, matchId: createdMatch.id, ratingBefore: player2Rating, ratingAfter: player2Rating + p2Change, ratingChange: p2Change }, { playerId: player3.id, matchId: createdMatch.id, ratingBefore: player3Rating, ratingAfter: player3Rating + p3Change, ratingChange: p3Change }, { playerId: player4.id, matchId: createdMatch.id, ratingBefore: player4Rating, ratingAfter: player4Rating + p4Change, ratingChange: p4Change }, ], }); // Update partnership stats await updatePartnershipStats(player1.id, player2.id, match.team1Score > match.team2Score, p1Change + p2Change); await updatePartnershipStats(player3.id, player4.id, match.team2Score > match.team1Score, p3Change + p4Change); // Add players to tournament if applicable if (match.eventId) { await prisma.eventParticipant.upsert({ where: { eventId_playerId: { eventId: match.eventId, playerId: player1.id, }, }, update: {}, create: { eventId: match.eventId, playerId: player1.id }, }); await prisma.eventParticipant.upsert({ where: { eventId_playerId: { eventId: match.eventId, playerId: player2.id, }, }, update: {}, create: { eventId: match.eventId, playerId: player2.id }, }); await prisma.eventParticipant.upsert({ where: { eventId_playerId: { eventId: match.eventId, playerId: player3.id, }, }, update: {}, create: { eventId: match.eventId, playerId: player3.id }, }); await prisma.eventParticipant.upsert({ where: { eventId_playerId: { eventId: match.eventId, playerId: player4.id, }, }, update: {}, create: { eventId: match.eventId, playerId: player4.id }, }); } importedMatches.push(createdMatch); } catch (error) { const matchNum = validMatches.indexOf(match) + 1; errors.push(`Match ${matchNum}: ${error instanceof Error ? error.message : "Unknown error"}`); } } return NextResponse.json({ importedCount: importedMatches.length, errorCount: errors.length, errors: errors.length > 0 ? errors : undefined, matches: importedMatches, }); } catch (error) { console.error("Error creating matches:", error); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } } async function findOrCreatePlayer(name: string) { const normalizedName = name.trim().toLowerCase(); let player = await prisma.player.findFirst({ where: { normalizedName }, }); if (!player) { player = await prisma.player.create({ data: { name: name.trim(), normalizedName, rating: 1000, currentElo: 1000, }, }); } return player; } async function updatePartnershipStats(player1Id: number, player2Id: number, won: boolean, eloChange: number) { // Ensure player1Id < player2Id for consistent key generation const [smallId, largeId] = player1Id < player2Id ? [player1Id, player2Id] : [player2Id, player1Id]; const existingStat = await prisma.partnershipStat.findFirst({ where: { player1Id: smallId, player2Id: largeId, }, }); if (existingStat) { await prisma.partnershipStat.update({ where: { id: existingStat.id }, data: { gamesPlayed: { increment: 1 }, wins: won ? { increment: 1 } : undefined, losses: won ? undefined : { increment: 1 }, totalEloChange: { increment: eloChange }, lastPlayed: new Date(), }, }); } else { await prisma.partnershipStat.create({ data: { player1Id: smallId, player2Id: largeId, gamesPlayed: 1, wins: won ? 1 : 0, losses: won ? 0 : 1, totalEloChange: eloChange, lastPlayed: new Date(), }, }); } }