<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('agent_profiles', function (Blueprint $table): void {
            $table->boolean('can_create_child_agent')->default(false)->after('can_grant_extra_rebate');
            $table->boolean('can_create_player')->default(true)->after('can_create_child_agent');
        });

        \Illuminate\Support\Facades\DB::table('agent_profiles')->update([
            'can_create_child_agent' => true,
            'can_create_player' => true,
        ]);

        \App\Support\AgentDefaultRolePermissions::ensurePlatformAgentRole();
        \App\Models\AdminUser::query()
            ->whereIn('id', \Illuminate\Support\Facades\DB::table('admin_user_agents')->pluck('admin_user_id'))
            ->each(static function (\App\Models\AdminUser $user): void {
                $agentNodeId = $user->primaryAgentNodeId();
                if ($agentNodeId !== null) {
                    $user->syncPrimaryPlatformAgentRole($agentNodeId);
                }
            });
    }

    public function down(): void
    {
        Schema::table('agent_profiles', function (Blueprint $table): void {
            $table->dropColumn(['can_create_child_agent', 'can_create_player']);
        });
    }
};
