package com.spot.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spot.dto.mq.AssetChangeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 资产/订单变动 MQ 推送服务
 * 在充值、提现、划转、下单等资金或订单变动后发送通知消息，供 WS 模块实时推送给客户端
 *
 * @author jean
 * @date 2026-05-06
 */
@Slf4j
@Service
public class AssetChangeMqService {

    @Value("${kafka.topic.change:SPOT_CHANGE}")
    private String changeTopic;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 发送资产/订单变动消息
     *
     * @param type    变动类型：asset-资产变动，order-订单变动
     * @param uid     用户ID
     * @param symbols 币种列表（资产变动）或交易对列表（订单变动）
     */
    public void sendChangeMessage(String type, Long uid, List<String> symbols) {
        if (uid == null || symbols == null || symbols.isEmpty()) {
            return;
        }
        try {
            AssetChangeMessage msg = new AssetChangeMessage();
            msg.setType(type);
            msg.setUid(uid);
            msg.setSymbols(symbols);

            String body = objectMapper.writeValueAsString(msg);
            kafkaTemplate.send(changeTopic, String.valueOf(uid), body);
            log.debug("变动消息发送成功: type={}, uid={}, symbols={}", type, uid, symbols);
        } catch (Exception e) {
            log.warn("发送变动消息失败: type={}, uid={}", type, uid, e);
        }
    }

    /**
     * 发送现货资产变动通知
     *
     * @param uid    用户ID
     * @param symbol 币种符号
     */
    public void sendSpotAssetChange(Long uid, String symbol) {
        sendChangeMessage(AssetChangeMessage.TYPE_ASSET, uid, Collections.singletonList(symbol));
    }
}
