<?php

use App\Models\Player;
use App\Models\AdminUser;
use App\Models\PlayerWallet;
use App\Models\TransferOrder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Services\Wallet\LotteryTransferService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Services\AgentSettlement\SettlementPaymentService;
use App\Services\AgentSettlement\AgentSettlementBadDebtService;

uses(RefreshDatabase::class);

function fundOpsAdminToken(): string
{
    $admin = AdminUser::query()->create([
        'username' => 'fund_ops_admin',
        'name' => 'Fund Ops',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($admin);

    return $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
}

test('admin cannot reverse transfer in pending reconcile main site timeout order', function (): void {
    $token = fundOpsAdminToken();

    $player = Player::query()->create([
        'site_code' => 'main',
        'site_player_id' => 'reverse-in-timeout',
        'username' => null,
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    TransferOrder::query()->create([
        'transfer_no' => 'TI_reverse_in_timeout',
        'player_id' => $player->id,
        'direction' => 'in',
        'currency_code' => 'NPR',
        'amount' => 500,
        'idempotent_key' => 'reverse-in-timeout-key',
        'status' => 'pending_reconcile',
        'external_request_payload' => null,
        'external_response_payload' => null,
        'external_ref_no' => null,
        'fail_reason' => 'main_site_timeout',
        'finished_at' => null,
    ]);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->postJson('/api/v1/admin/wallet/transfer-orders/TI_reverse_in_timeout/reverse')
        ->assertStatus(422);

    expect(TransferOrder::query()->where('transfer_no', 'TI_reverse_in_timeout')->value('status'))
        ->toBe('pending_reconcile');
});

test('transfer in timeout order list hides reverse action', function (): void {
    $token = fundOpsAdminToken();

    $player = Player::query()->create([
        'site_code' => 'main',
        'site_player_id' => 'list-in-timeout',
        'username' => null,
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    TransferOrder::query()->create([
        'transfer_no' => 'TI_list_in_timeout',
        'player_id' => $player->id,
        'direction' => 'in',
        'currency_code' => 'NPR',
        'amount' => 500,
        'idempotent_key' => 'list-in-timeout-key',
        'status' => 'pending_reconcile',
        'external_request_payload' => null,
        'external_response_payload' => null,
        'external_ref_no' => null,
        'fail_reason' => 'main_site_timeout',
        'finished_at' => null,
    ]);

    $items = $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/wallet/transfer-orders?player_id='.$player->id)
        ->assertOk()
        ->json('data.items');

    $item = collect($items)->firstWhere('transfer_no', 'TI_list_in_timeout');
    expect($item)->not->toBeNull()
        ->and($item['can_reverse'])->toBeFalse();
});

test('settlement payment idempotency key prevents duplicate records', 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(),
    ]);

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

    $admin = AdminUser::query()->create([
        'username' => 'payment_idem_admin',
        'name' => 'Payment Idem',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);

    $service = app(SettlementPaymentService::class);
    $meta = ['idempotency_key' => 'pay-idem-key-1'];

    $service->recordPayment($billId, 400, (int) $admin->id, $meta);
    $service->recordPayment($billId, 400, (int) $admin->id, $meta);

    expect(DB::table('payment_records')->where('settlement_bill_id', $billId)->count())->toBe(1);

    $bill = DB::table('settlement_bills')->where('id', $billId)->first();
    expect((int) $bill->paid_amount)->toBe(400)
        ->and((int) $bill->unpaid_amount)->toBe(600);
});

test('bad debt write off is idempotent when retried', 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-idem',
        'auth_source' => 'lottery_native',
        'funding_mode' => 'credit',
        'username' => 'bdidem',
        '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' => 8000,
        'rebate_amount' => 0,
        'adjustment_amount' => 0,
        'net_amount' => 8000,
        'paid_amount' => 0,
        'unpaid_amount' => 8000,
        'status' => 'overdue',
        'confirmed_at' => now(),
        'locked_at' => now(),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

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

    $service = app(AgentSettlementBadDebtService::class);
    $first = $service->writeOff($billId, 'uncollectible', (int) $admin->id);
    $second = $service->writeOff($billId, 'uncollectible', (int) $admin->id);

    expect($second)->toBe($first)
        ->and(DB::table('settlement_bills')->where('bill_type', 'bad_debt')->count())->toBe(1)
        ->and(DB::table('settlement_adjustments')->where('original_bill_id', $billId)->count())->toBe(1);
});

test('bad debt write off idempotency key prevents duplicate records', 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-idem-key',
        'auth_source' => 'lottery_native',
        'funding_mode' => 'credit',
        'username' => 'bdidemkey',
        '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' => 5000,
        'rebate_amount' => 0,
        'adjustment_amount' => 0,
        'net_amount' => 5000,
        'paid_amount' => 0,
        'unpaid_amount' => 5000,
        'status' => 'overdue',
        'confirmed_at' => now(),
        'locked_at' => now(),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

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

    $service = app(AgentSettlementBadDebtService::class);
    $key = 'bd-idem-key-1';
    $first = $service->writeOff($billId, 'uncollectible', (int) $admin->id, $key);
    $second = $service->writeOff($billId, 'uncollectible', (int) $admin->id, $key);

    expect($second)->toBe($first)
        ->and(DB::table('settlement_adjustments')->where('original_bill_id', $billId)->count())->toBe(1)
        ->and(DB::table('settlement_adjustments')->where('original_bill_id', $billId)->value('idempotency_key'))
        ->toBe($key);
});

test('out pending reconcile reverse still credits lottery wallet once', function (): void {
    $player = Player::query()->create([
        'site_code' => 'main',
        'site_player_id' => 'reverse-out-ok',
        'username' => null,
        'nickname' => null,
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

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

    $order = TransferOrder::query()->create([
        'transfer_no' => 'TO_reverse_out_ok',
        'player_id' => $player->id,
        'direction' => 'out',
        'currency_code' => 'NPR',
        'amount' => 400,
        'idempotent_key' => 'reverse-out-ok-key',
        'status' => 'pending_reconcile',
        'external_request_payload' => null,
        'external_response_payload' => null,
        'external_ref_no' => null,
        'fail_reason' => 'main_site_timeout',
        'finished_at' => null,
    ]);

    $service = app(LotteryTransferService::class);
    $service->reconcileTransferOrder($order, 'reverse', 'ok');

    $wallet->refresh();
    $order->refresh();

    expect((int) $wallet->balance)->toBe(1_400)
        ->and($order->status)->toBe('reversed');
});
