package shop.alien.store.service;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import shop.alien.store.config.UniPushProperties;

import java.util.List;
import java.util.Map;

/**
 * 调用 uniCloud URL 化云函数触发推送。请求体需与云函数内解析字段一致（示例见类注释）。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UniPushCloudInvokeService {

    private final UniPushProperties properties;

    /**
     * 向云函数 POST JSON，默认结构（云函数内自行读取并调用 uniPush.sendMessage）：
     * <pre>
     * {
     *   "push_clientid": ["cid1","cid2"],
     *   "title": "...",
     *   "content": "...",
     *   "payload": { }  // 可选，自定义透传
     * }
     * </pre>
     */
    public String sendToClientIds(List<String> pushClientIds, String title, String content, Map<String, Object> payload) {
        if (!properties.isEnabled() || StringUtils.isBlank(properties.getCloudFunctionUrl())) {
            log.debug("uni-push 云函数调用未启用或未配置 cloudFunctionUrl，跳过");
            return null;
        }
        if (pushClientIds == null || pushClientIds.isEmpty()) {
            log.warn("uni-push 推送跳过：pushClientIds 为空");
            return null;
        }

        JSONObject body = new JSONObject();
        body.put("push_clientid", pushClientIds);
        body.put("title", title != null ? title : "");
        body.put("content", content != null ? content : "");
        if (payload != null && !payload.isEmpty()) {
            body.put("payload", payload);
        }

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(properties.getConnectTimeoutMs());
        factory.setReadTimeout(properties.getReadTimeoutMs());
        RestTemplate restTemplate = new RestTemplate(factory);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (StringUtils.isNotBlank(properties.getAuthHeaderName())
                && StringUtils.isNotBlank(properties.getAuthHeaderValue())) {
            headers.set(properties.getAuthHeaderName(), properties.getAuthHeaderValue());
        }

        HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), headers);
        try {
            ResponseEntity<String> resp = restTemplate.postForEntity(
                    properties.getCloudFunctionUrl(), entity, String.class);
            String respBody = resp.getBody();
            log.info("uni-push 云函数调用完成, status={}, body={}", resp.getStatusCode(), respBody);
            return respBody;
        } catch (Exception e) {
            log.error("uni-push 云函数调用失败: {}", e.getMessage(), e);
            throw e;
        }
    }
}
