All files / web/src/app/api/player-stats/record-game route.ts

0% Statements 0/293
0% Branches 0/1
0% Functions 0/1
0% Lines 0/293

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { eq } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { db } from '@/db'
import type { GameStatsBreakdown } from '@/db/schema/player-stats'
import { playerStats } from '@/db/schema/player-stats'
import type {
  GameResult,
  PlayerGameResult,
  PlayerStatsData,
  RecordGameRequest,
  RecordGameResponse,
  StatsUpdate,
} from '@/lib/arcade/stats/types'
import { withAuth } from '@/lib/auth/withAuth'
import { canPerformAction } from '@/lib/classroom'
import { getUserId } from '@/lib/viewer'

/**
 * POST /api/player-stats/record-game
 *
 * Records a game result and updates player stats for all participants.
 * Supports cooperative games (team wins/losses) and competitive games.
 * Requires 'start-session' permission for each player being recorded.
 */
export const POST = withAuth(async (request) => {
  try {
    // 1. Authenticate user and get database user ID
    const userId = await getUserId()
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 2. Parse and validate request
    const body: RecordGameRequest = await request.json()
    const { gameResult } = body

    if (!gameResult || !gameResult.playerResults || gameResult.playerResults.length === 0) {
      return NextResponse.json(
        { error: 'Invalid game result: playerResults required' },
        { status: 400 }
      )
    }

    if (!gameResult.gameType) {
      return NextResponse.json({ error: 'Invalid game result: gameType required' }, { status: 400 })
    }

    // 3. Authorization: verify caller can record stats for ALL players
    for (const playerResult of gameResult.playerResults) {
      const canRecord = await canPerformAction(userId, playerResult.playerId, 'start-session')
      if (!canRecord) {
        return NextResponse.json(
          {
            error: `Not authorized to record stats for player ${playerResult.playerId}`,
          },
          { status: 403 }
        )
      }
    }

    // 4. Process each player's result
    const updates: StatsUpdate[] = []

    for (const playerResult of gameResult.playerResults) {
      const update = await recordPlayerResult(gameResult, playerResult)
      updates.push(update)
    }

    // 5. Return success response
    const response: RecordGameResponse = {
      success: true,
      updates,
    }

    return NextResponse.json(response)
  } catch (error) {
    console.error('❌ Failed to record game result:', error)
    return NextResponse.json(
      {
        error: 'Failed to record game result',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    )
  }
})

/**
 * Records stats for a single player's game result
 */
async function recordPlayerResult(
  gameResult: GameResult,
  playerResult: PlayerGameResult
): Promise<StatsUpdate> {
  const { playerId } = playerResult

  // 1. Fetch or create player stats
  const existingStats = await db
    .select()
    .from(playerStats)
    .where(eq(playerStats.playerId, playerId))
    .limit(1)
    .then((rows) => rows[0])

  const previousStats: PlayerStatsData = existingStats
    ? convertToPlayerStatsData(existingStats)
    : createDefaultPlayerStats(playerId)

  // 2. Calculate new stats
  const newStats: PlayerStatsData = { ...previousStats }

  // Always increment games played
  newStats.gamesPlayed++

  // Handle wins/losses (cooperative vs competitive)
  if (gameResult.metadata?.isTeamVictory !== undefined) {
    // Cooperative game: all players share outcome
    if (playerResult.won) {
      newStats.totalWins++
    } else {
      newStats.totalLosses++
    }
  } else {
    // Competitive/Solo: individual outcome
    if (playerResult.won) {
      newStats.totalWins++
    } else {
      newStats.totalLosses++
    }
  }

  // Update best time (if provided and improved)
  if (playerResult.completionTime) {
    if (!newStats.bestTime || playerResult.completionTime < newStats.bestTime) {
      newStats.bestTime = playerResult.completionTime
    }
  }

  // Update highest accuracy (if provided and improved)
  if (playerResult.accuracy !== undefined && playerResult.accuracy > newStats.highestAccuracy) {
    newStats.highestAccuracy = playerResult.accuracy
  }

  // Update per-game stats (JSON)
  const gameType = gameResult.gameType
  const currentGameStats: GameStatsBreakdown = newStats.gameStats[gameType] || {
    gamesPlayed: 0,
    wins: 0,
    losses: 0,
    bestTime: null,
    highestAccuracy: 0,
    averageScore: 0,
    lastPlayed: 0,
  }

  currentGameStats.gamesPlayed++
  if (playerResult.won) {
    currentGameStats.wins++
  } else {
    currentGameStats.losses++
  }

  // Update game-specific best time
  if (playerResult.completionTime) {
    if (!currentGameStats.bestTime || playerResult.completionTime < currentGameStats.bestTime) {
      currentGameStats.bestTime = playerResult.completionTime
    }
  }

  // Update game-specific highest accuracy
  if (
    playerResult.accuracy !== undefined &&
    playerResult.accuracy > currentGameStats.highestAccuracy
  ) {
    currentGameStats.highestAccuracy = playerResult.accuracy
  }

  // Update average score
  if (playerResult.score !== undefined) {
    const previousTotal = currentGameStats.averageScore * (currentGameStats.gamesPlayed - 1)
    currentGameStats.averageScore =
      (previousTotal + playerResult.score) / currentGameStats.gamesPlayed
  }

  currentGameStats.lastPlayed = gameResult.completedAt

  newStats.gameStats[gameType] = currentGameStats

  // Update favorite game type (most played)
  newStats.favoriteGameType = getMostPlayedGame(newStats.gameStats)

  // Update timestamps
  newStats.lastPlayedAt = new Date(gameResult.completedAt)
  newStats.updatedAt = new Date()

  // 3. Save to database
  if (existingStats) {
    // Update existing record
    await db
      .update(playerStats)
      .set({
        gamesPlayed: newStats.gamesPlayed,
        totalWins: newStats.totalWins,
        totalLosses: newStats.totalLosses,
        bestTime: newStats.bestTime,
        highestAccuracy: newStats.highestAccuracy,
        favoriteGameType: newStats.favoriteGameType,
        gameStats: newStats.gameStats as any, // Drizzle JSON type
        lastPlayedAt: newStats.lastPlayedAt,
        updatedAt: newStats.updatedAt,
      })
      .where(eq(playerStats.playerId, playerId))
  } else {
    // Insert new record
    await db.insert(playerStats).values({
      playerId: newStats.playerId,
      gamesPlayed: newStats.gamesPlayed,
      totalWins: newStats.totalWins,
      totalLosses: newStats.totalLosses,
      bestTime: newStats.bestTime,
      highestAccuracy: newStats.highestAccuracy,
      favoriteGameType: newStats.favoriteGameType,
      gameStats: newStats.gameStats as any,
      lastPlayedAt: newStats.lastPlayedAt,
      createdAt: newStats.createdAt,
      updatedAt: newStats.updatedAt,
    })
  }

  // 4. Return update summary
  return {
    playerId,
    previousStats,
    newStats,
    changes: {
      gamesPlayed: newStats.gamesPlayed - previousStats.gamesPlayed,
      wins: newStats.totalWins - previousStats.totalWins,
      losses: newStats.totalLosses - previousStats.totalLosses,
    },
  }
}

/**
 * Convert DB record to PlayerStatsData
 */
function convertToPlayerStatsData(dbStats: typeof playerStats.$inferSelect): PlayerStatsData {
  return {
    playerId: dbStats.playerId,
    gamesPlayed: dbStats.gamesPlayed,
    totalWins: dbStats.totalWins,
    totalLosses: dbStats.totalLosses,
    bestTime: dbStats.bestTime,
    highestAccuracy: dbStats.highestAccuracy,
    favoriteGameType: dbStats.favoriteGameType,
    gameStats: (dbStats.gameStats as Record<string, GameStatsBreakdown>) || {},
    lastPlayedAt: dbStats.lastPlayedAt,
    createdAt: dbStats.createdAt,
    updatedAt: dbStats.updatedAt,
  }
}

/**
 * Create default player stats for new player
 */
function createDefaultPlayerStats(playerId: string): PlayerStatsData {
  const now = new Date()
  return {
    playerId,
    gamesPlayed: 0,
    totalWins: 0,
    totalLosses: 0,
    bestTime: null,
    highestAccuracy: 0,
    favoriteGameType: null,
    gameStats: {},
    lastPlayedAt: null,
    createdAt: now,
    updatedAt: now,
  }
}

/**
 * Determine most-played game from game stats
 */
function getMostPlayedGame(gameStats: Record<string, GameStatsBreakdown>): string | null {
  const games = Object.entries(gameStats)
  if (games.length === 0) return null

  return games.reduce((mostPlayed, [gameType, stats]) => {
    const mostPlayedStats = gameStats[mostPlayed]
    return stats.gamesPlayed > (mostPlayedStats?.gamesPlayed || 0) ? gameType : mostPlayed
  }, games[0][0])
}