package cn.qihangerp.service.external.sph;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * 微信小店 OpenAPI：HTTPS JSON POST（与拼多多 {@link cn.qihangerp.service.external.pdd.PddPopClient} 对称，无 POP 签名）。
 *
 * @author guochengyu
 */
@Slf4j
@Component
public class WeixinShopEcHttpClient {

    private final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(15))
            .build();

    /**
     * @param urlWithQuery 已拼接 {@code access_token} 等 query 的完整 URL
     * @param jsonBody     请求体 JSON；允许为空则发空对象 {@code {}}
     */
    public String postJson(String urlWithQuery, String jsonBody, Duration readTimeout) throws Exception {
        String body = jsonBody == null || jsonBody.isBlank() ? "{}" : jsonBody;
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(urlWithQuery))
                .timeout(readTimeout != null ? readTimeout : Duration.ofSeconds(60))
                .header("Content-Type", "application/json; charset=utf-8")
                .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
                .build();
        long t0 = System.currentTimeMillis();
        HttpResponse<String> resp = httpClient.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        long ms = System.currentTimeMillis() - t0;
        if (log.isDebugEnabled()) {
            log.debug("weixin-ec POST url={} http={} costMs={} snippet={}",
                    WeixinShopEcLogSupport.redactAccessTokenInUrl(urlWithQuery),
                    resp.statusCode(),
                    ms,
                    WeixinShopEcLogSupport.snippet(resp.body(), 400));
        }
        return resp.body();
    }

    /**
     * 解析微信通用响应中的 {@code errcode}；{@code errcode==0} 视为业务成功。
     */
    public static boolean isBizOk(String raw) {
        if (raw == null || raw.isBlank()) {
            return false;
        }
        try {
            return JSON.parseObject(raw).getIntValue("errcode") == 0;
        } catch (Exception e) {
            return false;
        }
    }

    public static String formatWxError(String raw) {
        if (raw == null || raw.isBlank()) {
            return "empty response";
        }
        try {
            var o = JSON.parseObject(raw);
            return "errcode=" + o.getIntValue("errcode") + ", errmsg=" + o.getString("errmsg");
        } catch (Exception e) {
            return WeixinShopEcLogSupport.snippet(raw, 500);
        }
    }
}
