package com.ycwl.basic.integration.message.service;

import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.common.service.IntegrationFallbackService;
import com.ycwl.basic.integration.message.client.MessageClient;
import com.ycwl.basic.integration.message.dto.ChannelsResponse;
import com.ycwl.basic.integration.message.dto.MessageListData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class MessageIntegrationService {

    private final MessageClient client;
    private final IntegrationFallbackService fallbackService;

    private static final String SERVICE_NAME = "zt-message";

    public MessageListData listMessages(Integer page, Integer pageSize,
                                        String channelId, String title, String content, String sendBiz,
                                        String sentAtStart, String sentAtEnd,
                                        String createdAtStart, String createdAtEnd) {
        log.debug("查询消息列表 page={}, pageSize={}, channelId={}, title={}, sendBiz={}", page, pageSize, channelId, title, sendBiz);
        CommonResponse<MessageListData> resp = client.listMessages(page, pageSize, channelId, title, content, sendBiz,
                sentAtStart, sentAtEnd, createdAtStart, createdAtEnd);
        return handleResponse(resp, "查询消息列表失败");
    }

    public ChannelsResponse listChannels() {
        log.debug("查询消息通道列表");
        // 相对稳定的数据，使用fallback缓存
        return fallbackService.executeWithFallback(
                SERVICE_NAME,
                "channels",
                () -> {
                    CommonResponse<ChannelsResponse> resp = client.listChannels();
                    return handleResponse(resp, "查询通道列表失败");
                },
                ChannelsResponse.class
        );
    }

    private <T> T handleResponse(CommonResponse<T> response, String errorMessage) {
        if (response == null || !response.isSuccess()) {
            String msg = response != null && response.getMessage() != null
                    ? response.getMessage()
                    : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, SERVICE_NAME);
        }
        return response.getData();
    }
}
