package com.ssyf.task.websocket.msg;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ssyf.third.bmiss.model.LiveRoom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 消息分发中心
 */
@Slf4j
@Service
public class WsMessageDispatcher {

    // Spring 会自动将所有实现 WsMessageHandler 接口的 Bean 注入到这个 List 中
    @Autowired
    private List<WsMessageHandler> handlers;

    /**
     * 分发消息
     * @param rawMessage 原始消息字符串
     */
    public void dispatch(LiveRoom liveRoom, String token, String rawMessage) {
        Integer  roomId = liveRoom.getUser_id();
        String anchorName = liveRoom.getNick_name();
        try {
            if (!JSONUtil.isTypeJSON(rawMessage)) {
                return;
            }
            JSONObject json = JSONUtil.parseObj(rawMessage);
            
            // 获取路由关键字段
            String scene = json.getStr("scene");
            String type = json.getStr("type");

            if (scene == null || type == null) {
                return;
            }

            // 遍历策略列表寻找支持的处理器
            boolean handled = false;
            for (WsMessageHandler handler : handlers) {
                if (handler.supports(scene, type)) {
                    handler.handle(roomId, json, liveRoom , token);
                    handled = true;
                    break;
                }
            }
            
            if (!handled) {
                log.debug("[Room {}] No handler for scene={}, type={}", roomId, scene, type);
            }

        } catch (Exception e) {
            log.error("[Room {}] Dispatch error: {}", roomId, e.getMessage());
        }
    }
}