package com.fs.live.service;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过 HTTP 调用 fs-live-app，驱动 WebSocket 广播（与行为推送同源配置 liveWebSocketUrl）
 */
@Slf4j
@Service
public class LiveAppWebSocketNotifyService {

    @Autowired(required = false)
    private Environment environment;

    /** 通知 fs-live-app 向所有在线连接广播全局评论配置（cmd=liveCommentConfig） */
    public void broadcastCommentConfigRefresh() {
        postJson("/app/live/comment/broadcastConfig", Collections.emptyMap());
    }

    public void broadcastToLive(Long liveId, String fullMessageJson) {
        if (liveId == null || StringUtils.isEmpty(fullMessageJson)) {
            return;
        }
        Map<String, Object> body = new HashMap<>(2);
        body.put("liveId", liveId);
        body.put("message", fullMessageJson);
        postJson("/app/live/comment/broadcastToLive", body);
    }

    /**
     * 订单动效提示走消息队列的异步广播入口（高并发场景推荐）。
     * 会被消费者线程池异步发送，内部具备背压保护，高峰期可能丢弃。
     */
    public void broadcastOrderTipToLive(Long liveId, String fullMessageJson) {
        if (liveId == null || StringUtils.isEmpty(fullMessageJson)) {
            return;
        }
        Map<String, Object> body = new HashMap<>(2);
        body.put("liveId", liveId);
        body.put("message", fullMessageJson);
        postJson("/app/live/comment/broadcastOrderTip", body);
    }

    private void postJson(String path, Object body) {
        if (environment == null) {
            return;
        }
        String base = environment.getProperty("liveWebSocketUrl");
        if (StringUtils.isEmpty(base)) {
            log.debug("[live-app通知] 未配置 liveWebSocketUrl，跳过 {}", path);
            return;
        }
        String url = trimSlash(base) + path;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String json = JSONObject.toJSONString(body == null ? Collections.emptyMap() : body);
            HttpEntity<String> request = new HttpEntity<>(json, headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            log.info("[live-app通知] {} -> {}", path, response.getStatusCode());
        } catch (Exception e) {
            log.error("[live-app通知] 调用失败 url={}", url, e);
        }
    }

    private static String trimSlash(String base) {
        if (base.endsWith("/")) {
            return base.substring(0, base.length() - 1);
        }
        return base;
    }
}
