package com.fs.wx.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.fs.wx.dto.OrderQueryRequest;
import com.fs.wx.dto.OrderQueryResponse;
import com.fs.wx.service.OrderQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    private static final Logger log = LoggerFactory.getLogger(OrderQueryServiceImpl.class);

    private String apiBaseUrl = "https://tgpay.833006.net";

    private String secretKey = "YOUR_SECRET_KEY";

    private static final String ORDER_QUERY_PATH = "/tgPosp/services/payApi/orderQuery";
    private static final int SUCCESS_STATUS = 100;

    @Override
    public OrderQueryResponse queryOrder(OrderQueryRequest request) {
        String apiUrl = apiBaseUrl + ORDER_QUERY_PATH;
        String requestBody = JSONUtil.toJsonStr(request);

        log.info("Sending Order Query request to {}: {}", apiUrl, requestBody);

        HttpResponse response = null;
        try {
            response = HttpRequest.post(apiUrl)
                    .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                    .body(requestBody)
                    .timeout(10000)
                    .execute();

            String responseBody = response.body();
            log.info("Received Order Query response ({}): {}", response.getStatus(), responseBody);

            if (!response.isOk()) {
                throw new RuntimeException(String.format("API request failed with HTTP status %d: %s",
                        response.getStatus(), responseBody));
            }

            if (StrUtil.isBlank(responseBody)) {
                throw new RuntimeException("API response body is empty.");
            }

            OrderQueryResponse queryResponse = JSONUtil.toBean(responseBody, OrderQueryResponse.class, true); // Use lenient parsing for openId/openid


            if (queryResponse.getStatus() == null || queryResponse.getStatus() != SUCCESS_STATUS) {
                 log.error("API returned failure status [{}]: {}", queryResponse.getStatus(), queryResponse.getMessage());
                 throw new RuntimeException(String.format("API error [%d]: %s",
                         queryResponse.getStatus() != null ? queryResponse.getStatus() : -1,
                         queryResponse.getMessage()));
            }

            return queryResponse;

        } catch (Exception e) {
            log.error("Error during Order Query API call", e);
            throw new RuntimeException("Failed to query order: " + e.getMessage(), e);
        }
    }
}
