<?php

use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Services\Agent\AgentNodeService;
use App\Services\Agent\AgentProfileService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    $this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});

test('agent with overdue bill cannot create player', function (): void {
    $siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
    $rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');

    $super = AdminUser::query()->create([
        'username' => 'od_super',
        'name' => 'OD',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($super);

    $agent = app(AgentNodeService::class)->createChild($super, agentChildPayload([
        'parent_id' => $rootId,
        'code' => 'OD1',
        'name' => 'OD1',
        'username' => 'od_agent_user',
        'total_share_rate' => 50,
        'credit_limit' => 10000,
        'can_create_player' => true,
    ]));

    $admin = AdminUser::query()->where('username', 'od_agent_user')->first();
    expect($admin)->not->toBeNull();

    $periodId = (int) DB::table('settlement_periods')->insertGetId([
        'admin_site_id' => $siteId,
        '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' => 'agent',
        'owner_type' => 'agent',
        'owner_id' => $agent->id,
        'counterparty_type' => 'agent',
        'counterparty_id' => $rootId,
        'gross_win_loss' => 0,
        'rebate_amount' => 0,
        'adjustment_amount' => 0,
        'net_amount' => 500,
        'paid_amount' => 0,
        'unpaid_amount' => 500,
        'status' => 'overdue',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    expect(fn () => app(AgentProfileService::class)->assertActorMayCreatePlayer($admin))
        ->toThrow(\Illuminate\Validation\ValidationException::class);
});
