<?php

use App\Lottery\DrawStatus;
use App\Models\AdminUser;
use App\Models\Draw;
use App\Models\Player;
use App\Services\AgentSettlement\AgentSettlementReportQueryService;
use App\Services\AgentSettlement\SettlementPaymentService;
use App\Support\PlayerFundingMode;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

uses(RefreshDatabase::class);

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

test('record payment rejects bill that is not confirmed', function (): void {
    $siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
    $periodId = (int) DB::table('settlement_periods')->insertGetId([
        'admin_site_id' => $siteId,
        'period_start' => now()->subWeek(),
        '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' => 1,
        'net_amount' => 500,
        'unpaid_amount' => 500,
        'paid_amount' => 0,
        'status' => 'pending_confirm',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

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

    expect(fn () => app(SettlementPaymentService::class)->recordPayment($billId, 100, (int) $admin->id))
        ->toThrow(ValidationException::class);

    expect(DB::table('payment_records')->where('settlement_bill_id', $billId)->exists())->toBeFalse();
});

test('record payment rejects amount above unpaid balance', function (): void {
    $siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
    $periodId = (int) DB::table('settlement_periods')->insertGetId([
        'admin_site_id' => $siteId,
        'period_start' => now()->subWeek(),
        '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' => 1,
        'net_amount' => 500,
        'unpaid_amount' => 500,
        'paid_amount' => 0,
        'status' => 'confirmed',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

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

    expect(fn () => app(SettlementPaymentService::class)->recordPayment($billId, 600, (int) $admin->id))
        ->toThrow(ValidationException::class);

    expect(DB::table('payment_records')->where('settlement_bill_id', $billId)->exists())->toBeFalse();
});

test('settlement reports scope player win loss to agent subtree', function (): void {
    $siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
    $siteCode = (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
    $rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
    $service = app(\App\Services\Agent\AgentNodeService::class);
    $super = AdminUser::query()->create([
        'username' => 'report_scope_super',
        'name' => 'Super',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($super);

    $branch = $service->createChild($super, [
        'parent_id' => $rootId,
        'code' => 'report-branch',
        'name' => 'Report Branch',
    ]);
    $otherBranch = $service->createChild($super, [
        'parent_id' => $rootId,
        'code' => 'report-other',
        'name' => 'Report Other',
    ]);

    $periodStart = now()->subDay()->startOfDay()->toDateTimeString();
    $periodEnd = now()->addDay()->endOfDay()->toDateTimeString();
    $settledAt = now()->toDateTimeString();

    foreach ([$branch, $otherBranch] as $node) {
        $player = Player::query()->create([
            'site_code' => $siteCode,
            'site_player_id' => 'native:report-'.$node->code,
            'funding_mode' => PlayerFundingMode::CREDIT,
            'username' => 'report_'.$node->code,
            'default_currency' => 'NPR',
            'status' => 0,
            'agent_node_id' => $node->id,
        ]);

        $ticketItemId = createReportScopeTicketItem($player, 'T-'.$node->code);

        DB::table('share_ledger')->insert([
            'ticket_item_id' => $ticketItemId,
            'player_id' => $player->id,
            'agent_node_id' => $node->id,
            'agent_path' => json_encode([$node->id]),
            'share_snapshot' => json_encode([
                'total_shares' => [(string) $node->code => 1.0],
                'chain_codes' => [(string) $node->code],
            ]),
            'game_win_loss' => $node->id === $branch->id ? 1000 : 2000,
            'basic_rebate' => 0,
            'shared_net_win_loss' => $node->id === $branch->id ? 1000 : 2000,
            'allocations_json' => json_encode([]),
            'settled_at' => $settledAt,
            'created_at' => $settledAt,
            'updated_at' => $settledAt,
        ]);
    }

    $operator = AdminUser::query()->create([
        'username' => 'report_scope_ops',
        'name' => 'Ops',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantReportScopeAgentOperator($operator, $branch);

    $reports = app(AgentSettlementReportQueryService::class);
    $scoped = $reports->playerWinLoss($operator, 0, $periodStart, $periodEnd);
    $all = $reports->playerWinLoss($super, 0, $periodStart, $periodEnd);

    expect($scoped)->toHaveCount(1)
        ->and((int) $scoped[0]['game_win_loss'])->toBe(1000)
        ->and($all)->toHaveCount(2);
});

function createReportScopeTicketItem(Player $player, string $ticketNo): int
{
    $draw = Draw::query()->create([
        'draw_no' => 'DRAW-'.$ticketNo,
        'business_date' => now()->toDateString(),
        'sequence_no' => random_int(1, 9999),
        'status' => DrawStatus::Open->value,
        'current_result_version' => 0,
        'settle_version' => 0,
        'is_reopened' => false,
    ]);

    $orderId = (int) DB::table('ticket_orders')->insertGetId([
        'order_no' => 'ORD-'.$ticketNo,
        'player_id' => $player->id,
        'draw_id' => $draw->id,
        'currency_code' => 'NPR',
        'total_bet_amount' => 10_000,
        'total_rebate_amount' => 0,
        'total_actual_deduct' => 10_000,
        'total_estimated_payout' => 0,
        'status' => 'confirmed',
        'submit_source' => 'h5',
        'client_trace_id' => null,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    return (int) DB::table('ticket_items')->insertGetId([
        'ticket_no' => $ticketNo,
        'order_id' => $orderId,
        'player_id' => $player->id,
        'draw_id' => $draw->id,
        'normalized_number' => '1234',
        'play_code' => 'big',
        'dimension' => 2,
        'unit_bet_amount' => 10_000,
        'total_bet_amount' => 10_000,
        'rebate_rate_snapshot' => 0,
        'commission_rate_snapshot' => 0,
        'actual_deduct_amount' => 10_000,
        'combination_count' => 1,
        'estimated_max_payout' => 0,
        'risk_locked_amount' => 0,
        'status' => 'settled_lose',
        'win_amount' => 0,
        'jackpot_win_amount' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
}

function grantReportScopeAgentOperator(AdminUser $admin, \App\Models\AgentNode $agent): void
{
    $now = now();
    $roleId = DB::table('admin_roles')->insertGetId([
        'slug' => 'report_ops_'.$admin->id,
        'code' => 'report_ops_'.$admin->id,
        'name' => 'Report Ops',
        'status' => 1,
        'is_system' => false,
        'sort_order' => 0,
        'created_at' => $now,
        'updated_at' => $now,
    ]);

    $actionIds = DB::table('admin_menu_actions')
        ->whereIn('permission_code', ['agent.node.view'])
        ->pluck('id');

    foreach ($actionIds as $actionId) {
        DB::table('admin_role_menu_actions')->insert([
            'role_id' => $roleId,
            'menu_action_id' => (int) $actionId,
        ]);
    }

    DB::table('admin_user_site_roles')->insert([
        'admin_user_id' => $admin->id,
        'site_id' => (int) $agent->admin_site_id,
        'role_id' => $roleId,
        'granted_at' => $now,
    ]);

    DB::table('admin_user_agents')->insert([
        'admin_user_id' => $admin->id,
        'agent_node_id' => (int) $agent->id,
        'is_primary' => true,
        'granted_at' => $now,
    ]);

    DB::table('admin_user_agent_roles')->insert([
        'admin_user_id' => $admin->id,
        'agent_node_id' => (int) $agent->id,
        'role_id' => $roleId,
        'granted_at' => $now,
    ]);
}
