<?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('agent_nodes') || ! Schema::hasTable('agent_profiles')) {
            return;
        }

        $defaults = config('agent_line_defaults', []);
        $now = now();

        // 整批包在事务中：避免中途某条失败时部分根代理已补 profile、部分缺失的中间态。
        DB::transaction(function () use ($defaults, $now): void {
            $roots = DB::table('agent_nodes')->where('depth', 0)->get(['id']);

            foreach ($roots as $root) {
                $nodeId = (int) $root->id;
                if (DB::table('agent_profiles')->where('agent_node_id', $nodeId)->exists()) {
                    continue;
                }

                DB::table('agent_profiles')->insert([
                    'agent_node_id' => $nodeId,
                    'total_share_rate' => (float) ($defaults['total_share_rate'] ?? 100),
                    'credit_limit' => (int) ($defaults['credit_limit'] ?? 0) > 0
                        ? (int) $defaults['credit_limit']
                        : 1_000_000,
                    'allocated_credit' => 0,
                    'used_credit' => 0,
                    'rebate_limit' => (float) ($defaults['rebate_limit'] ?? 0.005),
                    'default_player_rebate' => (float) ($defaults['default_player_rebate'] ?? 0.005),
                    'can_grant_extra_rebate' => true,
                    'can_create_child_agent' => true,
                    'can_create_player' => true,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        });
    }

    public function down(): void
    {
        // 非破坏性：不回删已补档案。
    }
};
