<?php

/**
 * 文件功能：双色球彩票前台接口测试
 *
 * 覆盖当前期查询、机选、购票、历史和我的购票记录。
 */

namespace Tests\Feature;

use App\Models\GameConfig;
use App\Models\LotteryIssue;
use App\Models\LotteryTicket;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Redis;
use Tests\TestCase;

/**
 * 类功能：验证双色球彩票控制器的核心前台行为。
 */
class LotteryControllerTest extends TestCase
{
    use RefreshDatabase;

    /**
     * 方法功能：初始化双色球默认配置。
     */
    protected function setUp(): void
    {
        parent::setUp();

        GameConfig::updateOrCreate(
            ['game_key' => 'lottery'],
            [
                'name' => 'Lottery',
                'icon' => 'lottery',
                'description' => 'Lottery Game',
                'enabled' => true,
                'params' => [
                    'ticket_price' => 100,
                ],
            ]
        );
    }

    /**
     * 方法功能：验证可以获取当前彩票期次。
     */
    public function test_can_get_current(): void
    {
        /** @var \App\Models\User $user */
        $user = User::factory()->create();

        $issue = LotteryIssue::create([
            'issue_no' => '2026101',
            'status' => 'open',
            'red1' => 0,
            'red2' => 0,
            'red3' => 0,
            'blue' => 0,
            'pool_amount' => 5000,
            'carry_amount' => 0,
            'is_super_issue' => false,
            'no_winner_streak' => 0,
            'total_tickets' => 0,
            'payout_amount' => 0,
            'sell_closes_at' => now()->addMinutes(1),
            'draw_at' => now()->addMinutes(2),
        ]);

        $response = $this->actingAs($user)->getJson(route('lottery.current'));

        $response->assertStatus(200);
        $response->assertJsonStructure(['issue' => ['id', 'issue_no', 'status', 'pool_amount']]);
        $this->assertEquals($issue->id, $response->json('issue.id'));
    }

    /**
     * 方法功能：验证可以生成机选号码。
     */
    public function test_can_quick_pick(): void
    {
        /** @var \App\Models\User $user */
        $user = User::factory()->create();

        $response = $this->actingAs($user)->getJson(route('lottery.quick-pick', ['count' => 2]));

        $response->assertStatus(200);
        $response->assertJsonStructure(['numbers']);
        $this->assertCount(2, $response->json('numbers'));
    }

    /**
     * 方法功能：验证金币不足时无法购票。
     */
    public function test_cannot_buy_without_enough_gold(): void
    {
        /** @var \App\Models\User $user */
        $user = User::factory()->create(['jjb' => 50]);

        LotteryIssue::create([
            'issue_no' => '2026101',
            'status' => 'open',
            'red1' => 0,
            'red2' => 0,
            'red3' => 0,
            'blue' => 0,
            'pool_amount' => 5000,
            'carry_amount' => 0,
            'is_super_issue' => false,
            'no_winner_streak' => 0,
            'total_tickets' => 0,
            'payout_amount' => 0,
            'sell_closes_at' => now()->addMinutes(1),
            'draw_at' => now()->addMinutes(2),
        ]);

        $response = $this->actingAs($user)->postJson(route('lottery.buy'), [
            'numbers' => [
                [
                    'reds' => [1, 2, 3],
                    'blue' => 4,
                ],
            ],
            'quick_pick' => false,
        ]);

        $response->assertStatus(422); // Exception thrown with 422
    }

    /**
     * 方法功能：验证金币充足时可以购票并广播右下角通知。
     */
    public function test_can_buy_with_enough_gold(): void
    {
        /** @var \App\Models\User $user */
        $user = User::factory()->create(['jjb' => 200]);

        LotteryIssue::create([
            'issue_no' => '2026101',
            'status' => 'open',
            'red1' => 0,
            'red2' => 0,
            'red3' => 0,
            'blue' => 0,
            'pool_amount' => 5000,
            'carry_amount' => 0,
            'is_super_issue' => false,
            'no_winner_streak' => 0,
            'total_tickets' => 0,
            'payout_amount' => 0,
            'sell_closes_at' => now()->addMinutes(1),
            'draw_at' => now()->addMinutes(2),
        ]);

        $response = $this->actingAs($user)->postJson(route('lottery.buy'), [
            'numbers' => [
                [
                    'reds' => [1, 2, 3],
                    'blue' => 4,
                ],
            ],
            'quick_pick' => false,
        ]);

        $response->assertStatus(200);
        $response->assertJson(['status' => 'success']);

        $this->assertEquals(100, $user->fresh()->jjb); // cost is 100 per ticket

        $messages = Redis::lrange('room:1:messages', 0, -1);
        $publicMessage = collect($messages)
            ->map(fn (string $item) => json_decode($item, true))
            ->first(fn (array $item) => ($item['to_user'] ?? null) === '大家'
                && ($item['toast_notification']['title'] ?? null) === '🎟️ 有人购买双色球'
                && str_contains((string) ($item['toast_notification']['message'] ?? ''), $user->username));

        $this->assertNotNull($publicMessage);
        $this->assertFalse((bool) ($publicMessage['is_secret'] ?? true));
        $this->assertStringContainsString($user->username, (string) ($publicMessage['toast_notification']['message'] ?? ''));
        $this->assertSame('🎟️', $publicMessage['toast_notification']['icon'] ?? null);
    }

    /**
     * 方法功能：验证可以查询历史期次。
     */
    public function test_can_get_history(): void
    {
        /** @var \App\Models\User $user */
        $user = User::factory()->create();

        LotteryIssue::create([
            'issue_no' => '2026100',
            'status' => 'settled',
            'red1' => 1,
            'red2' => 2,
            'red3' => 3,
            'blue' => 4,
            'pool_amount' => 5000,
            'carry_amount' => 0,
            'is_super_issue' => false,
            'no_winner_streak' => 0,
            'total_tickets' => 10,
            'payout_amount' => 1000,
            'draw_at' => now(),
        ]);

        $response = $this->actingAs($user)->getJson(route('lottery.history'));

        $response->assertStatus(200);
        $response->assertJsonStructure(['issues']);
        $this->assertCount(1, $response->json('issues'));
    }

    /**
     * 方法功能：验证可以查询我的购票记录。
     */
    public function test_can_get_my_tickets(): void
    {
        /** @var \App\Models\User $user */
        $user = User::factory()->create();

        $issue = LotteryIssue::create([
            'issue_no' => '2026100',
            'status' => 'settled',
            'red1' => 1,
            'red2' => 2,
            'red3' => 3,
            'blue' => 4,
            'pool_amount' => 5000,
            'carry_amount' => 0,
            'is_super_issue' => false,
            'no_winner_streak' => 0,
            'total_tickets' => 10,
            'payout_amount' => 1000,
            'draw_at' => now(),
        ]);

        LotteryTicket::create([
            'issue_id' => $issue->id,
            'user_id' => $user->id,
            'red1' => 1,
            'red2' => 2,
            'red3' => 3,
            'blue' => 4,
            'amount' => 100,
            'is_quick_pick' => 0,
        ]);

        $response = $this->actingAs($user)->getJson(route('lottery.my'));

        $response->assertStatus(200);
        $response->assertJsonStructure(['tickets']);
        $this->assertCount(1, $response->json('tickets'));
    }
}
