package com.sino.mci.channel.wecom;

import com.sino.mci.channel.common.dto.SendMessageRequest;
import com.sino.mci.channel.common.dto.SendMessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

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

@Slf4j
@Component
public class WeComBotSender {

    private static final String DEFAULT_WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s";

    private final RestTemplate restTemplate = new RestTemplate();

    public SendMessageResult send(SendMessageRequest request) {
        SendMessageResult result = new SendMessageResult();
        String key = getString(request.getExtra(), "account_id");
        if (key == null || key.isBlank()) {
            result.setSuccess(false);
            result.setMessage("企微群机器人缺少 webhook key");
            return result;
        }

        String contentType = request.getContentType() == null ? "text" : request.getContentType().toLowerCase();
        Map<String, Object> body = buildBody(contentType, request.getContent());
        if (body == null) {
            result.setSuccess(false);
            result.setMessage("不支持的消息类型: " + contentType);
            return result;
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        try {
            String url = String.format(DEFAULT_WEBHOOK_URL, key);
            restTemplate.postForEntity(url, entity, String.class);
            result.setSuccess(true);
        } catch (Exception e) {
            log.warn("[WeComBot] 发送失败", e);
            result.setSuccess(false);
            result.setMessage("企微群机器人发送失败: " + e.getMessage());
        }
        return result;
    }

    private Map<String, Object> buildBody(String contentType, Map<String, Object> content) {
        Map<String, Object> body = new HashMap<>();
        switch (contentType) {
            case "text" -> {
                body.put("msgtype", "text");
                Map<String, Object> text = new HashMap<>();
                text.put("content", getString(content, "text"));
                body.put("text", text);
            }
            case "markdown" -> {
                body.put("msgtype", "markdown");
                Map<String, Object> markdown = new HashMap<>();
                markdown.put("content", getString(content, "text"));
                body.put("markdown", markdown);
            }
            default -> {
                return null;
            }
        }
        return body;
    }

    private String getString(Map<String, Object> map, String key) {
        if (map == null) {
            return null;
        }
        Object value = map.get(key);
        return value == null ? null : value.toString();
    }
}
