/**
 * Migration Worker: Legacy Team Unlocks → Per-Player Prop Unlocks
 *
 * Policy A (Grandfather Access):
 * - All existing team-level unlocks grant access to individual player props
 * - New rows created with cost_forecasts=0, source='team_migration'
 * - Idempotent via ON CONFLICT DO NOTHING
 *
 * Usage: npx tsx src/workers/migrate-team-unlocks.ts [--dry-run]
 */
import dotenv from 'dotenv';
import path from 'path';
dotenv.config({ path: path.join(__dirname, '../../.env') });

import pool from '../db';

const DRY_RUN = process.argv.includes('--dry-run');

async function migrate() {
  console.log(`[migrate-team-unlocks] Starting migration${DRY_RUN ? ' (DRY RUN)' : ''}...`);

  // 1. Query all legacy team unlock rows
  const { rows: teamUnlocks } = await pool.query(
    'SELECT id, user_id, event_id, team, was_weatherman FROM rm_team_props_unlocks'
  );

  console.log(`[migrate-team-unlocks] Found ${teamUnlocks.length} legacy team unlock(s)`);

  let totalMigrated = 0;
  let totalSkipped = 0;

  for (const unlock of teamUnlocks) {
    // 2. Find all PLAYER_PROP precomputed rows matching (event_id, team_side)
    const { rows: playerProps } = await pool.query(
      `SELECT id, player_name FROM rm_forecast_precomputed
       WHERE event_id = $1 AND team_side = $2 AND forecast_type = 'PLAYER_PROP' AND status = 'ACTIVE'`,
      [unlock.event_id, unlock.team]
    );

    console.log(`  Legacy unlock ${unlock.id}: event=${unlock.event_id}, team=${unlock.team} → ${playerProps.length} player prop(s)`);

    for (const prop of playerProps) {
      if (DRY_RUN) {
        console.log(`    [DRY RUN] Would migrate: player=${prop.player_name}, asset=${prop.id}`);
        totalMigrated++;
        continue;
      }

      // 3. Insert per-player unlock (idempotent)
      const { rows: inserted } = await pool.query(
        `INSERT INTO rm_player_prop_unlocks (user_id, forecast_asset_id, cost_forecasts, source, was_weatherman)
         VALUES ($1, $2, 0, 'team_migration', $3)
         ON CONFLICT (user_id, forecast_asset_id) DO NOTHING
         RETURNING id`,
        [unlock.user_id, prop.id, unlock.was_weatherman]
      );

      if (inserted.length > 0) {
        // 4. Record in migration map
        await pool.query(
          `INSERT INTO rm_unlock_migration_map (legacy_team_unlock_id, new_player_prop_unlock_id, event_id, team, player_name)
           VALUES ($1, $2, $3, $4, $5)`,
          [unlock.id, inserted[0].id, unlock.event_id, unlock.team, prop.player_name]
        );
        totalMigrated++;
      } else {
        totalSkipped++;
      }
    }
  }

  console.log(`[migrate-team-unlocks] Complete: ${totalMigrated} migrated, ${totalSkipped} skipped (already existed)`);
  await pool.end();
}

migrate().catch((err) => {
  console.error('[migrate-team-unlocks] Fatal error:', err);
  process.exit(1);
});
