package com.sino.mci.send.service;

import com.sino.mci.send.entity.SendRecord;
import com.sino.mci.shared.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class SendCallbackService {

    private static final int CALLBACK_STATUS_DELIVERED = 1;
    private static final int CALLBACK_STATUS_FAILED = 3;

    private final RestTemplate restTemplate;

    public void sendCallback(SendRecord record) {
        if (record == null || !StringUtils.hasText(record.getCallbackUrl())) {
            return;
        }
        String event;
        int status;
        if (record.getSendStatus() != null && record.getSendStatus() == 2) {
            event = "delivered";
            status = CALLBACK_STATUS_DELIVERED;
        } else {
            event = "failed";
            status = CALLBACK_STATUS_FAILED;
        }
        Map<String, Object> payload = new HashMap<>();
        payload.put("task_id", record.getTaskId());
        payload.put("record_id", record.getId());
        payload.put("conversation_id", record.getConversationId());
        payload.put("person_id", record.getPersonId());
        payload.put("channel_type", record.getChannelType());
        payload.put("event", event);
        payload.put("status", status);
        payload.put("channel_result", parseChannelResult(record.getChannelResult()));
        payload.put("event_time", record.getFinishTime() != null ? record.getFinishTime() : LocalDateTime.now());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
        try {
            restTemplate.postForEntity(record.getCallbackUrl(), entity, String.class);
            log.info("发送回调成功: recordId={}, event={}", record.getId(), event);
        } catch (Exception e) {
            log.warn("发送回调失败: recordId={}, url={}", record.getId(), record.getCallbackUrl(), e);
        }
    }

    private Object parseChannelResult(String channelResult) {
        if (!StringUtils.hasText(channelResult)) {
            return new HashMap<>();
        }
        Object result = JsonUtils.fromJson(channelResult, Object.class);
        return result != null ? result : new HashMap<>();
    }
}
