<?php

use App\Models\Draw;
use App\Models\Player;
use App\Models\TicketItem;
use App\Models\TicketOrder;
use App\Services\Admin\AdminReportQueryService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('provider profit report aggregates split ticket items by provider', function (): void {
    $player = Player::query()->create([
        'site_code' => 'main', 'site_player_id' => 'provider-report-1', 'username' => 'provider_report',
        'nickname' => null, 'default_currency' => 'NPR', 'status' => 0,
    ]);
    $draw = Draw::query()->create([
        'draw_no' => 'RPT-PROVIDER-001', 'business_date' => '2026-07-10', 'sequence_no' => 1, 'status' => 'settled',
        'start_time' => now()->subHour(), 'close_time' => now(), 'draw_time' => now()->addHour(),
        'cooling_end_time' => null, 'result_source' => null, 'current_result_version' => 1, 'settle_version' => 1, 'is_reopened' => false,
    ]);
    $order = TicketOrder::query()->create([
        'order_no' => 'RPT-PROVIDER-ORD', 'player_id' => $player->id, 'draw_id' => $draw->id, 'currency_code' => 'NPR',
        'total_bet_amount' => 3000, 'total_rebate_amount' => 0, 'total_actual_deduct' => 3000,
        'total_estimated_payout' => 0, 'status' => 'settled', 'submit_source' => 'h5', 'client_trace_id' => 'provider-report-trace',
    ]);
    foreach ([['SG', 'Singapore', 1000, 100], ['MY', 'Malaysia', 2000, 500]] as [$code, $name, $bet, $payout]) {
        TicketItem::query()->create([
            'ticket_no' => 'RPT-'.$code, 'order_id' => $order->id, 'player_id' => $player->id, 'draw_id' => $draw->id,
            'provider_code' => $code, 'provider_name' => $name, 'original_number' => '1234', 'normalized_number' => '1234',
            'play_code' => 'big', 'dimension' => 4, 'digit_slot' => null, 'bet_mode' => 'single', 'unit_bet_amount' => $bet,
            'total_bet_amount' => $bet, 'rebate_rate_snapshot' => '0.0000', 'commission_rate_snapshot' => '0.0000',
            'actual_deduct_amount' => $bet, 'win_amount' => $payout, 'jackpot_win_amount' => 0, 'status' => 'settled',
        ]);
    }

    $rows = app(AdminReportQueryService::class)->providerProfitPaginated('2026-07-10', '2026-07-10', 1, 20)->items();

    expect($rows)->toHaveCount(2)
        ->and($rows[0]->provider_code)->toBe('MY')
        ->and((int) $rows[0]->total_bet_minor)->toBe(2000)
        ->and((int) $rows[0]->approx_house_gross_minor)->toBe(1500)
        ->and($rows[1]->provider_code)->toBe('SG')
        ->and((int) $rows[1]->total_payout_minor)->toBe(100);
});
