<?php

use App\Models\Player;
use App\Models\PlayerWallet;
use App\Services\Player\PlayerCreditService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

test('credit line hold does not change wallet balance', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $extra = json_decode((string) ($site->extra_json ?? '{}'), true);
    if (! is_array($extra)) {
        $extra = [];
    }
    $extra['credit_line_mode'] = true;
    DB::table('admin_sites')->where('id', $site->id)->update([
        'extra_json' => json_encode($extra),
        'updated_at' => now(),
    ]);

    $player = Player::query()->create([
        'site_code' => (string) $site->code,
        'agent_node_id' => (int) DB::table('agent_nodes')->where('depth', 0)->value('id'),
        'site_player_id' => 'cl-p1',
        'auth_source' => 'lottery_native',
        'funding_mode' => 'credit',
        'username' => 'cl1',
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    PlayerWallet::query()->create([
        'player_id' => $player->id,
        'wallet_type' => 'lottery',
        'currency_code' => 'NPR',
        'balance' => 50000,
        'frozen_balance' => 0,
        'status' => 0,
        'version' => 0,
    ]);

    DB::table('player_credit_accounts')->insert([
        'player_id' => $player->id,
        'credit_limit' => 10000,
        'used_credit' => 0,
        'frozen_credit' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $walletBefore = (int) PlayerWallet::query()->where('player_id', $player->id)->value('balance');

    app(PlayerCreditService::class)->assertMayPlaceBet($player, 500);

    $walletAfter = (int) PlayerWallet::query()->where('player_id', $player->id)->value('balance');
    expect($walletAfter)->toBe($walletBefore);
    expect((int) DB::table('player_credit_accounts')->where('player_id', $player->id)->value('used_credit'))->toBe(5);
    expect(DB::table('credit_ledger')->where('reason', 'bet_hold')->where('owner_id', $player->id)->exists())->toBeTrue();
});
