package com.ttstd.signaling.controller;

import com.ttstd.signaling.manager.ConnectionRequestManager;
import com.ttstd.signaling.manager.SessionManager;
import com.ttstd.signaling.manager.SignalMetrics;
import com.ttstd.signaling.model.DeviceInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台管理 REST 接口：为 WebRTCSignalServerWeb 提供服务器运行态查询。
 * 所有接口均以 {@code /api/admin} 为前缀，并由 {@link AdminAuthFilter} 统一鉴权。
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    private final SessionManager sessionManager;
    private final ConnectionRequestManager connectionRequestManager;
    private final SignalMetrics metrics;
    private final long startTime = System.currentTimeMillis();

    public AdminController(SessionManager sessionManager,
                           ConnectionRequestManager connectionRequestManager,
                           SignalMetrics metrics) {
        this.sessionManager = sessionManager;
        this.connectionRequestManager = connectionRequestManager;
        this.metrics = metrics;
    }

    /** 仪表盘汇总数据：设备在线情况、待确认连接、流量指标与运行时长。 */
    @GetMapping("/dashboard")
    public Map<String, Object> dashboard() {
        List<DeviceInfo> devices = sessionManager.getAllDeviceDetails();
        long controllers = devices.stream()
                .filter(d -> "CONTROLLER".equals(d.deviceType()) && d.online()).count();
        long controlled = devices.stream()
                .filter(d -> "CONTROLLED".equals(d.deviceType()) && d.online()).count();
        long online = devices.stream().filter(DeviceInfo::online).count();
        long offline = devices.size() - online;

        Map<String, Object> data = new HashMap<>();
        data.put("serverStartTime", startTime);
        data.put("currentTime", System.currentTimeMillis());
        data.put("uptimeMs", System.currentTimeMillis() - startTime);
        data.put("totalDevices", devices.size());
        data.put("onlineDevices", online);
        data.put("offlineDevices", offline);
        data.put("onlineControllers", controllers);
        data.put("onlineControlled", controlled);
        data.put("pendingConnections", connectionRequestManager.getPendingRequests().size());
        data.put("metrics", metrics.snapshot());
        return data;
    }

    /** 设备列表，可按 deviceType（CONTROLLER / CONTROLLED）过滤。 */
    @GetMapping("/devices")
    public List<DeviceInfo> devices(@RequestParam(required = false) String type) {
        List<DeviceInfo> all = sessionManager.getAllDeviceDetails();
        if (type == null || type.isBlank()) {
            return all;
        }
        final String upper = type.toUpperCase();
        return all.stream()
                .filter(d -> upper.equals(d.deviceType()))
                .collect(Collectors.toList());
    }

    /** 当前处于“待被控端确认”状态的连接请求。 */
    @GetMapping("/connections")
    public List<Map<String, Object>> connections() {
        return connectionRequestManager.getPendingRequests();
    }

    /** 服务器连接治理配置项（去重窗口、确认超时、WebSocket 端点等）。 */
    @GetMapping("/config")
    public Map<String, Object> config() {
        Map<String, Object> data = new HashMap<>();
        data.put("dedupWindowMs", connectionRequestManager.getDedupWindowMs());
        data.put("requestTimeoutMs", connectionRequestManager.getRequestTimeoutMs());
        data.put("websocketEndpoint", "/ws/signal");
        data.put("serverPort", 8080);
        return data;
    }

    /** 健康检查。 */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> data = new HashMap<>();
        data.put("status", "UP");
        data.put("currentTime", System.currentTimeMillis());
        data.put("onlineDevices", sessionManager.getOnlineCount());
        return data;
    }
}
