package com.ecep.contract.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ecep.contract.service.WebSocketService;

/**
 * WebSocket测试控制器
 * 提供API端点用于测试WebSocket消息发送功能
 */
@RestController
@RequestMapping("/api/websocket")
public class WebSocketController {

    private final WebSocketService webSocketService;

    @Autowired
    public WebSocketController(WebSocketService webSocketService) {
        this.webSocketService = webSocketService;
    }

    /**
     * 发送广播消息
     * 
     * @param payload 消息负载，包含message字段
     * @return 响应实体
     */
    @PostMapping("/broadcast")
    public ResponseEntity<?> broadcastMessage(@RequestBody Map<String, String> payload) {
        String message = payload.get("message");
        if (message == null || message.isEmpty()) {
            return ResponseEntity.badRequest().body("消息内容不能为空");
        }

        webSocketService.broadcastMessage(message);
        return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "消息已广播",
                "activeSessions", webSocketService.getActiveSessionCount()));
    }

    /**
     * 发送系统通知
     * 
     * @param payload 通知负载，包含notification字段
     * @return 响应实体
     */
    @PostMapping("/notification")
    public ResponseEntity<?> sendNotification(@RequestBody Map<String, String> payload) {
        String notification = payload.get("notification");
        if (notification == null || notification.isEmpty()) {
            return ResponseEntity.badRequest().body("通知内容不能为空");
        }

        webSocketService.sendSystemNotification(notification);
        return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "通知已发送",
                "activeSessions", webSocketService.getActiveSessionCount()));
    }

    /**
     * 获取WebSocket连接状态
     * 
     * @return 响应实体，包含当前活跃连接数
     */
    @GetMapping("/status")
    public ResponseEntity<?> getStatus() {
        return ResponseEntity.ok(Map.of(
                "success", true,
                "activeSessions", webSocketService.getActiveSessionCount(),
                "message", "WebSocket服务运行正常"));
    }
}