<?php

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

uses(RefreshDatabase::class);

test('admin credit ledger index returns credit player ledger rows', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $siteId = (int) $site->id;
    $siteCode = (string) $site->code;

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

    $player = Player::query()->create([
        'site_code' => $siteCode,
        'site_player_id' => 'native:credit-ledger-admin',
        'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
        'funding_mode' => PlayerFundingMode::CREDIT,
        'username' => 'credit_admin_flow',
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    DB::table('credit_ledger')->insert([
        'owner_type' => 'player',
        'owner_id' => $player->id,
        'amount' => -500,
        'reason' => 'bet_hold',
        'ref_type' => 'bet',
        'ref_id' => null,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

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

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/credit-ledger?admin_site_id='.$siteId.'&settlement_period_id='.$periodId)
        ->assertOk()
        ->assertJsonPath('data.ledger_source', 'settlement_ledger')
        ->assertJsonPath('data.total', 1)
        ->assertJsonPath('data.items.0.entry_kind', 'credit')
        ->assertJsonPath('data.items.0.player_id', $player->id)
        ->assertJsonPath('data.items.0.biz_type', 'bet_hold')
        ->assertJsonPath('data.items.0.ledger_source', 'credit_ledger')
        ->assertJsonPath('data.items.0.funding_mode', PlayerFundingMode::CREDIT)
        ->assertJsonPath('data.items.0.available_actions', ['view_player']);
});

test('admin credit ledger simple display merges release and loss per ticket', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $siteId = (int) $site->id;
    $siteCode = (string) $site->code;

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

    $player = Player::query()->create([
        'site_code' => $siteCode,
        'site_player_id' => 'native:simple-flow',
        'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
        'funding_mode' => PlayerFundingMode::CREDIT,
        'username' => 'simple_flow',
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    $now = now();
    DB::table('credit_ledger')->insert([
        [
            'owner_type' => 'player',
            'owner_id' => $player->id,
            'amount' => -1200,
            'reason' => 'bet_hold',
            'ref_type' => 'bet',
            'ref_id' => null,
            'created_at' => $now->copy()->subMinutes(2),
            'updated_at' => $now->copy()->subMinutes(2),
        ],
        [
            'owner_type' => 'player',
            'owner_id' => $player->id,
            'amount' => 1200,
            'reason' => 'bet_hold_release',
            'ref_type' => 'ticket_item',
            'ref_id' => 88,
            'created_at' => $now,
            'updated_at' => $now,
        ],
        [
            'owner_type' => 'player',
            'owner_id' => $player->id,
            'amount' => -1200,
            'reason' => 'game_settlement_loss',
            'ref_type' => 'ticket_item',
            'ref_id' => 88,
            'created_at' => $now,
            'updated_at' => $now,
        ],
    ]);

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

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/credit-ledger?admin_site_id='.$siteId.'&settlement_period_id='.$periodId.'&bet_flow_display=simple')
        ->assertOk()
        ->assertJsonPath('data.ledger_source', 'credit_ledger')
        ->assertJsonPath('data.total', 1)
        ->assertJsonCount(1, 'data.items')
        ->assertJsonPath('data.items.0.biz_type', 'game_settlement')
        ->assertJsonPath('data.items.0.signed_amount', -1200);
});

test('admin credit ledger simple display shows win amount for winning bet', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $siteId = (int) $site->id;
    $siteCode = (string) $site->code;

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

    $player = Player::query()->create([
        'site_code' => $siteCode,
        'site_player_id' => 'native:win-flow',
        'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
        'funding_mode' => PlayerFundingMode::CREDIT,
        'username' => 'win_flow',
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    $now = now();

    $drawId = (int) DB::table('draws')->insertGetId([
        'draw_no' => 'WIN-FLOW-001',
        'business_date' => now()->toDateString(),
        'sequence_no' => 1,
        'status' => 'settled',
        'created_at' => $now,
        'updated_at' => $now,
    ]);

    $orderId = (int) DB::table('ticket_orders')->insertGetId([
        'order_no' => 'ORD-WIN-001',
        'player_id' => $player->id,
        'draw_id' => $drawId,
        'currency_code' => 'NPR',
        'total_bet_amount' => 800,
        'total_actual_deduct' => 800,
        'status' => 'settled',
        'created_at' => $now,
        'updated_at' => $now,
    ]);

    DB::table('ticket_items')->insert([
        'id' => 99,
        'ticket_no' => 'TI-WIN-99',
        'order_id' => $orderId,
        'player_id' => $player->id,
        'draw_id' => $drawId,
        'normalized_number' => '1234',
        'play_code' => 'straight',
        'total_bet_amount' => 800,
        'actual_deduct_amount' => 800,
        'status' => 'settled_win',
        'win_amount' => 2500,
        'created_at' => $now,
        'updated_at' => $now,
    ]);

    DB::table('credit_ledger')->insert([
        [
            'owner_type' => 'player',
            'owner_id' => $player->id,
            'amount' => -800,
            'reason' => 'bet_hold',
            'ref_type' => 'bet',
            'ref_id' => null,
            'created_at' => $now->copy()->subMinutes(2),
            'updated_at' => $now->copy()->subMinutes(2),
        ],
        [
            'owner_type' => 'player',
            'owner_id' => $player->id,
            'amount' => 800,
            'reason' => 'bet_hold_release',
            'ref_type' => 'ticket_item',
            'ref_id' => 99,
            'created_at' => $now,
            'updated_at' => $now,
        ],
        [
            'owner_type' => 'player',
            'owner_id' => $player->id,
            'amount' => 2500,
            'reason' => 'game_settlement_win',
            'ref_type' => 'ticket_item',
            'ref_id' => 99,
            'created_at' => $now,
            'updated_at' => $now,
        ],
    ]);

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

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/credit-ledger?admin_site_id='.$siteId.'&settlement_period_id='.$periodId.'&bet_flow_display=simple')
        ->assertOk()
        ->assertJsonPath('data.ledger_source', 'credit_ledger')
        ->assertJsonPath('data.total', 1)
        ->assertJsonCount(1, 'data.items')
        ->assertJsonPath('data.items.0.biz_type', 'game_settlement')
        ->assertJsonPath('data.items.0.signed_amount', 2500);
});

test('settlement periods include pipeline credit and share counts', function (): void {
    $site = DB::table('admin_sites')->where('is_default', true)->first();
    $siteId = (int) $site->id;
    $siteCode = (string) $site->code;

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

    $player = Player::query()->create([
        'site_code' => $siteCode,
        'site_player_id' => 'native:pipeline-1',
        'funding_mode' => PlayerFundingMode::CREDIT,
        'username' => 'pipe_user',
        'default_currency' => 'NPR',
        'status' => 0,
    ]);

    DB::table('credit_ledger')->insert([
        'owner_type' => 'player',
        'owner_id' => $player->id,
        'amount' => -100,
        'reason' => 'bet_hold',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

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

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/settlement-periods?admin_site_id='.$siteId)
        ->assertOk()
        ->assertJsonPath('data.items.0.id', $periodId)
        ->assertJsonPath('data.items.0.pipeline.credit_ledger_count', 1)
        ->assertJsonPath('data.items.0.pipeline.share_ledger_count', 0);
});
