<?php

/**
 * 文件功能：后台首页控制台
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Room;
use App\Models\User;
use App\Services\ChatStateService;
use Illuminate\View\View;

/**
 * 类功能：负责后台首页仪表盘的汇总统计展示。
 */
class DashboardController extends Controller
{
    /**
     * 注入聊天室状态服务，供仪表盘读取实时在线数据。
     */
    public function __construct(
        private readonly ChatStateService $chatState,
    ) {}

    /**
     * 显示后台首页与全局统计
     */
    public function index(): View
    {
        $onlineUsernames = collect();

        foreach ($this->chatState->getAllActiveRoomIds() as $roomId) {
            // 使用在线名单服务的懒清理结果，保证统计口径与聊天室在线列表一致。
            $onlineUsernames = $onlineUsernames->merge(array_keys($this->chatState->getRoomUsers($roomId)));
        }

        $stats = [
            'total_users' => User::count(),
            'total_rooms' => Room::count(),
            'online_users' => $onlineUsernames->unique()->count(),
            // 更多统计指标以后再发掘
        ];

        return view('admin.dashboard', compact('stats'));
    }
}
