package com.xindazhou.message.service.impl;

import com.corundumstudio.socketio.SocketIOServer;
import com.xindazhou.message.service.PushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 推送服务实现
 *
 * @author xindazhou
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PushServiceImpl implements PushService {

    private final SocketIOServer socketIOServer;

    @Override
    public void pushStatusUpdate(Long userId, Long vehicleId, Map<String, Object> statusData) {
        String room = "user:" + userId;
        pushToRoom(room, "vehicle_status_update", Map.of(
                "vehicleId", vehicleId,
                "status", statusData,
                "timestamp", System.currentTimeMillis()
        ));
    }

    @Override
    public void pushInboxMessage(Long userId, Map<String, Object> messageData) {
        String room = "user:" + userId;
        pushToRoom(room, "inbox_message", messageData);
    }

    @Override
    public void pushToRoom(String room, String event, Object data) {
        try {
            socketIOServer.getRoomOperations(room).sendEvent(event, data);
            log.debug("推送消息到房间: room={}, event={}", room, event);
        } catch (Exception e) {
            log.error("推送消息到房间失败: room={}, event={}", room, event, e);
        }
    }

    @Override
    public void pushToUser(Long userId, String event, Object data) {
        // TODO: 根据 userId 查找对应的 SocketIOClient，然后推送
        // 可以通过 Redis 存储 userId -> sessionId 的映射关系
        String room = "user:" + userId;
        pushToRoom(room, event, data);
    }

}

