<?php

use App\Models\AgentProfile;
use App\Services\Agent\AgentProfileService;
use App\Services\AgentSettlement\BetSettlementSnapshotBuilder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

test('share snapshot uses profile at build time not after change', function (): void {
    $siteId = (int) DB::table('admin_sites')->insertGetId([
        'code' => 'snap-line',
        'name' => 'snap',
        'is_default' => false,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $rootId = (int) DB::table('agent_nodes')->insertGetId([
        'admin_site_id' => $siteId,
        'parent_id' => null,
        'depth' => 0,
        'path' => '/snap-line',
        'code' => 'snap-line',
        'name' => 'Root',
        'status' => 1,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    AgentProfile::query()->create([
        'agent_node_id' => $rootId,
        'total_share_rate' => 25,
        'credit_limit' => 10000,
        'allocated_credit' => 0,
        'used_credit' => 0,
        'rebate_limit' => 0.01,
        'default_player_rebate' => 0.005,
    ]);

    $playerId = (int) DB::table('players')->insertGetId([
        'site_code' => 'snap-line',
        'agent_node_id' => $rootId,
        'site_player_id' => 'snap-p1',
        'username' => 'snap1',
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $player = \App\Models\Player::query()->findOrFail($playerId);
    $builder = app(BetSettlementSnapshotBuilder::class);
    $first = $builder->buildForPlayer($player);

    AgentProfile::query()->where('agent_node_id', $rootId)->update(['total_share_rate' => 50]);

    $stored = json_encode($first['total_shares']);
    $second = $builder->buildForPlayer($player->fresh());

    expect($stored)->toContain('"snap-line":25');
    expect($second['total_shares']['snap-line'])->toBe(50.0);
});
