<?php

use App\Models\AdminUser;
use App\Models\Player;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

uses(RefreshDatabase::class);

test('admin can write off player bill bad debt and complete period when all settled', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $agentId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');

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

    $player = Player::query()->create([
        'site_code' => (string) $site->code,
        'agent_node_id' => $agentId,
        'site_player_id' => 'bd-p1',
        'auth_source' => 'lottery_native',
        'funding_mode' => 'credit',
        'username' => 'bduser',
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    $billId = (int) DB::table('settlement_bills')->insertGetId([
        'settlement_period_id' => $periodId,
        'bill_type' => 'player',
        'owner_type' => 'player',
        'owner_id' => $player->id,
        'counterparty_type' => 'agent',
        'counterparty_id' => $agentId,
        'gross_win_loss' => 10000,
        'rebate_amount' => 0,
        'adjustment_amount' => 0,
        'platform_rounding_adjustment' => 0,
        'net_amount' => 10000,
        'paid_amount' => 0,
        'unpaid_amount' => 10000,
        'status' => 'overdue',
        'confirmed_at' => now(),
        'locked_at' => now(),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $admin = AdminUser::query()->create([
        'username' => 'bad_debt_super',
        'name' => 'Bad Debt',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($admin);
    $token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->postJson('/api/v1/admin/settlement-bills/'.$billId.'/bad-debt-write-off', [
            'reason' => 'uncollectible',
        ])
        ->assertOk()
        ->assertJsonPath('data.original_bill_id', $billId);

    $this->assertDatabaseHas('settlement_bills', [
        'id' => $billId,
        'status' => 'settled',
        'unpaid_amount' => 0,
    ]);

    $this->assertDatabaseHas('settlement_adjustments', [
        'original_bill_id' => $billId,
        'adjustment_type' => 'bad_debt',
        'amount' => 10000,
    ]);

    $this->assertDatabaseHas('settlement_periods', [
        'id' => $periodId,
        'status' => 'completed',
    ]);
});

test('bound agent with settlement manage cannot write off bad debt', 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');

    $periodId = (int) DB::table('settlement_periods')->insertGetId([
        'admin_site_id' => $siteId,
        'period_start' => now()->subDays(7),
        'period_end' => now(),
        'status' => 'closed',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $billId = (int) DB::table('settlement_bills')->insertGetId([
        'settlement_period_id' => $periodId,
        'bill_type' => 'agent',
        'owner_type' => 'agent',
        'owner_id' => $rootId,
        'counterparty_type' => 'platform',
        'counterparty_id' => 0,
        'net_amount' => 5000,
        'paid_amount' => 0,
        'unpaid_amount' => 5000,
        'status' => 'confirmed',
        'confirmed_at' => now(),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $admin = AdminUser::query()->create([
        'username' => 'bad_debt_bound_root',
        'name' => 'Bad Debt Bound Root',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);

    DB::table('admin_user_agents')->insert([
        'admin_user_id' => $admin->id,
        'agent_node_id' => $rootId,
        'is_primary' => true,
        'granted_at' => now(),
    ]);
    $admin->syncPrimaryPlatformAgentRole($rootId);
    $token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->postJson('/api/v1/admin/settlement-bills/'.$billId.'/bad-debt-write-off', [
            'reason' => 'should fail',
        ])
        ->assertForbidden();
});
