package com.emotion.controller;

import com.emotion.dto.request.WebSocketRequest;
import com.emotion.dto.websocket.ConnectRequest;
import com.emotion.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;

import javax.validation.Valid;
import java.security.Principal;

/**
 * WebSocket聊天控制器
 * 使用规范的请求对象封装参数，符合项目开发规则
 * 
 * @author huazhongmin
 * @date 2025-09-08
 */
@Slf4j
@Controller
@MessageMapping("/chat")
public class ChatWebSocketController {
    
    @Autowired
    private WebSocketService webSocketService;
    
    /**
     * 处理聊天消息
     * 
     * @param webSocketRequest WebSocket请求对象
     * @param headerAccessor   消息头访问器
     * @param principal        用户主体
     */
    @MessageMapping("/send")
    public void handleChatMessage(@Valid @Payload WebSocketRequest webSocketRequest,
            SimpMessageHeaderAccessor headerAccessor,
            Principal principal) {
        String sessionId = headerAccessor.getSessionId();
        webSocketService.handleChatMessage(webSocketRequest, sessionId, principal);
    }
    
    /**
     * 处理用户连接
     * 
     * @param connectRequest 连接请求对象
     * @param headerAccessor 消息头访问器
     * @param principal      用户主体
     */
    @MessageMapping("/connect")
    public void connectUser(@Payload ConnectRequest connectRequest,
            SimpMessageHeaderAccessor headerAccessor,
            Principal principal) {
        String sessionId = headerAccessor.getSessionId();
        webSocketService.handleUserConnect(connectRequest, sessionId, principal);
    }
    
    /**
     * 处理用户断开连接
     * 
     * @param headerAccessor 消息头访问器
     * @param principal      用户主体
     */
    @MessageMapping("/disconnect")
    public void disconnectUser(SimpMessageHeaderAccessor headerAccessor, Principal principal) {
        String sessionId = headerAccessor.getSessionId();
        webSocketService.handleUserDisconnect(sessionId, principal);
    }
    
    /**
     * 处理心跳消息
     * 
     * @param headerAccessor 消息头访问器
     * @param principal      用户主体
     */
    @MessageMapping("/heartbeat")
    public void heartbeat(SimpMessageHeaderAccessor headerAccessor, Principal principal) {
        String sessionId = headerAccessor.getSessionId();
        webSocketService.handleHeartbeat(sessionId, principal);
    }
}