<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('player_credit_accounts')) {
            return;
        }

        if (Schema::hasTable('players') && Schema::hasColumn('players', 'funding_mode')) {
            DB::table('players')
                ->where('funding_mode', 'credit')
                ->whereNotExists(function ($query): void {
                    $query->selectRaw('1')
                        ->from('player_credit_accounts')
                        ->whereColumn('player_credit_accounts.player_id', 'players.id');
                })
                ->orderBy('id')
                ->select('id')
                ->chunkById(500, function ($players): void {
                    $now = now();
                    $rows = [];
                    foreach ($players as $player) {
                        $rows[] = [
                            'player_id' => (int) $player->id,
                            'credit_limit' => 0,
                            'used_credit' => 0,
                            'frozen_credit' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    if ($rows !== []) {
                        DB::table('player_credit_accounts')->insertOrIgnore($rows);
                    }
                }, 'id');
        }
    }

    public function down(): void
    {
        // 兼容回填迁移，不回滚既有表结构。
    }
};
