package com.ssyf.ws.handler.system;


import com.ssyf.ws.constants.CommandType;
import com.ssyf.ws.domain.Command;
import com.ssyf.ws.domain.WsMessage;
import com.ssyf.ws.handler.CommandHandler;
import com.ssyf.ws.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PostConstruct;
import java.io.IOException;


/**
 * 认证命令处理器
 * 处理认证相关的命令
 */
@Slf4j
@Component
public class AuthHandler implements CommandHandler {

    private final MessageDispatcher messageDispatcher;

    public AuthHandler(MessageDispatcher messageDispatcher) {
        this.messageDispatcher = messageDispatcher;
    }

    /**
     * 初始化时注册处理器
     */
    @PostConstruct
    public void init() {
        messageDispatcher.registerHandler(CommandType.AUTH_REQUEST, this);
        log.info("认证命令处理器注册完成");
    }

    @Override
    public void handle(Command command, WebSocketSession session) {
        WsMessage message = command.getOriginalMessage();
        
        // TODO: 实现具体的认证逻辑
        // 这里可以验证token、权限等
        
        // 认证成功响应

        log.info("认证处理完成: userId={}", command.getSession().getUserId());
    }

    /**
     * 发送响应消息
     */
    private void sendResponse(WebSocketSession session, WsMessage response) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(JsonUtils.toJson(response)));
            }
        } catch (IOException e) {
            log.error("发送认证响应失败", e);
        }
    }
}