package com.ruoyi.app.omgpay;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/** Stage-only HTTP boundary for OMG QueryTradeInfo V5. */
@Component
public class OmgPaymentQueryGateway {
    static final String STAGE_QUERY_URL =
            "https://payment-stage.funpoint.com.tw/Cashier/QueryTradeInfo/V5";
    private static final int MAX_RESPONSE_BYTES = 32 * 1024;
    private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
            .setConnectTimeout(5_000)
            .setConnectionRequestTimeout(5_000)
            .setSocketTimeout(10_000)
            .build();

    public String query(Map<String, String> fields) {
        List<NameValuePair> form = new ArrayList<>();
        fields.forEach((name, value) -> form.add(new BasicNameValuePair(name, value)));
        HttpPost post = new HttpPost(STAGE_QUERY_URL);
        post.setEntity(new UrlEncodedFormEntity(form, StandardCharsets.UTF_8));
        try (CloseableHttpClient client = HttpClients.custom()
                .setDefaultRequestConfig(REQUEST_CONFIG)
                .disableRedirectHandling()
                .build();
             CloseableHttpResponse response = client.execute(post)) {
            int status = response.getStatusLine().getStatusCode();
            if (status < 200 || status >= 300 || response.getEntity() == null
                    || response.getEntity().getContentLength() > MAX_RESPONSE_BYTES) {
                throw new IllegalStateException("OMG query returned an invalid HTTP response");
            }
            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            if (bytes.length > MAX_RESPONSE_BYTES) {
                throw new IllegalStateException("OMG query response is oversized");
            }
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (IOException exception) {
            throw new IllegalStateException("OMG query request failed", exception);
        }
    }
}
