<?php

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

uses(RefreshDatabase::class);

test('overdue player cannot place bet on credit line', 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' => 'od-p1',
        'auth_source' => 'lottery_native',
        'funding_mode' => 'credit',
        'username' => 'od1',
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 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(),
    ]);

    $periodId = (int) DB::table('settlement_periods')->insertGetId([
        'admin_site_id' => (int) $site->id,
        'period_start' => now()->subWeek(),
        'period_end' => now()->subDay(),
        'status' => 'closed',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    DB::table('settlement_bills')->insert([
        'settlement_period_id' => $periodId,
        'bill_type' => 'player',
        'owner_type' => 'player',
        'owner_id' => $player->id,
        'counterparty_type' => 'agent',
        'counterparty_id' => $player->agent_node_id,
        'gross_win_loss' => 1000,
        'rebate_amount' => 0,
        'adjustment_amount' => 0,
        'net_amount' => 1000,
        'paid_amount' => 0,
        'unpaid_amount' => 1000,
        'status' => 'overdue',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    expect(fn () => app(PlayerCreditService::class)->assertMayPlaceBet($player, 100))
        ->toThrow(\Illuminate\Validation\ValidationException::class);
});
