<?php

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

/**
 * 将未归属玩家挂到对应主站根代理（与 agent_nodes depth=0 1:1）。
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! \Illuminate\Support\Facades\Schema::hasColumn('players', 'agent_node_id')) {
            return;
        }

        $roots = DB::table('agent_nodes as an')
            ->join('admin_sites as s', 's.id', '=', 'an.admin_site_id')
            ->where('an.depth', 0)
            ->get(['an.id as root_id', 's.code as site_code']);

        foreach ($roots as $root) {
            DB::table('players')
                ->where('site_code', (string) $root->site_code)
                ->whereNull('agent_node_id')
                ->update(['agent_node_id' => (int) $root->root_id]);
        }
    }

    public function down(): void
    {
        // 不回滚归属，避免误清空业务绑定。
    }
};
