<?php

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

uses(RefreshDatabase::class);

test('reverse bet hold is idempotent', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $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' => 'reverse-hold-p1',
        'auth_source' => 'lottery_native',
        'funding_mode' => 'credit',
        'username' => 'reverse_hold_1',
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

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

    $credit = app(PlayerCreditService::class);
    $credit->assertMayPlaceBet($player, 200);
    expect((int) DB::table('player_credit_accounts')->where('player_id', $player->id)->value('used_credit'))->toBe(2);

    $credit->reverseBetHold($player, 200, 999);
    expect((int) DB::table('player_credit_accounts')->where('player_id', $player->id)->value('used_credit'))->toBe(0);

    $credit->reverseBetHold($player, 200, 999);
    expect((int) DB::table('player_credit_accounts')->where('player_id', $player->id)->value('used_credit'))->toBe(0);

    expect(DB::table('credit_ledger')
        ->where('owner_type', 'player')
        ->where('owner_id', $player->id)
        ->where('reason', 'bet_hold_release')
        ->where('ref_type', 'ticket_order')
        ->where('ref_id', 999)
        ->count())->toBe(1);
});
