<?php

/**
 * 文件功能：后台仪表盘统计功能测试
 *
 * 覆盖后台首页在线人数卡片展示，确保仪表盘统计口径与聊天室在线名单一致。
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace Tests\Feature\Feature;

use App\Models\Room;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Redis;
use Tests\TestCase;

/**
 * 类功能：验证后台仪表盘核心统计数据的展示。
 */
class AdminDashboardControllerTest extends TestCase
{
    use RefreshDatabase;

    /**
     * 每个测试前清空 Redis，避免在线名单缓存影响断言结果。
     */
    protected function setUp(): void
    {
        parent::setUp();

        Redis::flushall();
    }

    /**
     * 验证后台仪表盘会显示去重后的在线人数。
     */
    public function test_dashboard_displays_unique_online_user_count(): void
    {
        $siteOwner = User::factory()->create([
            'id' => 1,
            'username' => 'site-owner',
        ]);

        $roomOne = Room::create(['room_name' => '后台房间一']);
        $roomTwo = Room::create(['room_name' => '后台房间二']);

        // 同一用户重复出现在多个房间时，仪表盘应按全局去重后的在线人数展示。
        Redis::hset("room:{$roomOne->id}:users", 'alice', json_encode(['username' => 'alice'], JSON_UNESCAPED_UNICODE));
        Redis::setex("room:{$roomOne->id}:alive:alice", 90, 1);
        Redis::hset("room:{$roomTwo->id}:users", 'alice', json_encode(['username' => 'alice'], JSON_UNESCAPED_UNICODE));
        Redis::setex("room:{$roomTwo->id}:alive:alice", 90, 1);
        Redis::hset("room:{$roomTwo->id}:users", 'bob', json_encode(['username' => 'bob'], JSON_UNESCAPED_UNICODE));
        Redis::setex("room:{$roomTwo->id}:alive:bob", 90, 1);

        $response = $this->actingAs($siteOwner)->get(route('admin.dashboard'));

        $response->assertOk();
        $response->assertSee('当前在线人数');
        $response->assertSee('2');
    }
}
