#!/usr/bin/env npx tsx
/**
 * Apply Transactions - Update Player.team based on PlayerTransaction records
 * Ensures player teams reflect their current 2026 roster assignments
 */

require('dotenv').config({ path: '.env.local' });
require('dotenv').config({ path: '.env' });

import { getSportsDb, isSportsDbEnabled } from '../lib/sportsDb';

async function main() {
  console.log('🔄 Apply Player Transactions');
  console.log('='.repeat(50));

  if (!isSportsDbEnabled()) {
    console.error('❌ SportsDB not enabled');
    process.exit(1);
  }

  const prisma = getSportsDb();

  // Get all transactions
  const transactions = await prisma.playerTransaction.findMany({
    orderBy: { transactionDate: 'desc' },
  });

  console.log(`\n📋 Found ${transactions.length} transactions to apply\n`);

  let updated = 0;
  let notFound = 0;
  let alreadyCorrect = 0;

  for (const tx of transactions) {
    // Find the player
    const player = await prisma.player.findFirst({
      where: {
        name: { equals: tx.playerName, mode: 'insensitive' },
        league: tx.league,
      },
    });

    if (!player) {
      console.log(`  ⚠️  ${tx.playerName} (${tx.league}): Player not found`);
      notFound++;
      continue;
    }

    // Check if team needs updating
    const currentTeam = player.team?.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 3) || '';
    const newTeam = tx.toTeam.toUpperCase();

    if (currentTeam === newTeam || player.team === newTeam) {
      alreadyCorrect++;
      continue;
    }

    // Update the player's team
    await prisma.player.update({
      where: { id: player.id },
      data: {
        team: tx.toTeam,
        updatedAt: new Date(),
      },
    });

    console.log(`  ✅ ${tx.playerName}: ${player.team} → ${tx.toTeam}`);
    updated++;
  }

  console.log('\n' + '='.repeat(50));
  console.log(`📊 Summary:`);
  console.log(`   Updated: ${updated}`);
  console.log(`   Already correct: ${alreadyCorrect}`);
  console.log(`   Not found: ${notFound}`);

  // Also normalize any remaining old-format team names
  console.log('\n🔧 Normalizing team name formats...');

  const TEAM_NORMALIZATIONS: Record<string, string> = {
    'LOS_ANGELES_LAKERS_NBA': 'LAL',
    'BOSTON_CELTICS_NBA': 'BOS',
    'GOLDEN_STATE_WARRIORS_NBA': 'GSW',
    'DALLAS_MAVERICKS_NBA': 'DAL',
    'MIAMI_HEAT_NBA': 'MIA',
    'BROOKLYN_NETS_NBA': 'BKN',
    'PHOENIX_SUNS_NBA': 'PHX',
    'DENVER_NUGGETS_NBA': 'DEN',
    'MILWAUKEE_BUCKS_NBA': 'MIL',
    'PHILADELPHIA_76ERS_NBA': 'PHI',
    'ATLANTA_HAWKS_NBA': 'ATL',
    'CHICAGO_BULLS_NBA': 'CHI',
    'CLEVELAND_CAVALIERS_NBA': 'CLE',
    'DETROIT_PISTONS_NBA': 'DET',
    'INDIANA_PACERS_NBA': 'IND',
    'NEW_YORK_KNICKS_NBA': 'NYK',
    'ORLANDO_MAGIC_NBA': 'ORL',
    'TORONTO_RAPTORS_NBA': 'TOR',
    'WASHINGTON_WIZARDS_NBA': 'WAS',
    'CHARLOTTE_HORNETS_NBA': 'CHA',
    'HOUSTON_ROCKETS_NBA': 'HOU',
    'MEMPHIS_GRIZZLIES_NBA': 'MEM',
    'NEW_ORLEANS_PELICANS_NBA': 'NOP',
    'SAN_ANTONIO_SPURS_NBA': 'SAS',
    'OKLAHOMA_CITY_THUNDER_NBA': 'OKC',
    'PORTLAND_TRAIL_BLAZERS_NBA': 'POR',
    'UTAH_JAZZ_NBA': 'UTA',
    'SACRAMENTO_KINGS_NBA': 'SAC',
    'MINNESOTA_TIMBERWOLVES_NBA': 'MIN',
    'LOS_ANGELES_CLIPPERS_NBA': 'LAC',
  };

  let normalized = 0;
  for (const [oldName, newName] of Object.entries(TEAM_NORMALIZATIONS)) {
    const result = await prisma.player.updateMany({
      where: { team: oldName },
      data: { team: newName },
    });
    if (result.count > 0) {
      console.log(`  ${oldName} → ${newName}: ${result.count} players`);
      normalized += result.count;
    }
  }

  console.log(`\n   Normalized: ${normalized} players`);
  console.log('\n✅ Done!');
}

main().catch(console.error);
