package com.ruoyi.app.omgpay;

import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/** Strictly decodes OMG's form-like query response without losing signed fields. */
@Component
public class OmgQueryResponseParser {
    static final int MAX_RESPONSE_CHARS = 32 * 1024;

    public Map<String, String> parse(String rawResponse) {
        if (rawResponse == null || rawResponse.isBlank() || rawResponse.length() > MAX_RESPONSE_CHARS) {
            throw new IllegalArgumentException("OMG query response is empty or oversized");
        }
        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        for (String pair : rawResponse.split("&", -1)) {
            if (pair.isEmpty()) {
                continue;
            }
            int separator = pair.indexOf('=');
            if (separator < 1) {
                throw new IllegalArgumentException("OMG query response field is malformed");
            }
            String name = URLDecoder.decode(pair.substring(0, separator), StandardCharsets.UTF_8);
            String value = URLDecoder.decode(pair.substring(separator + 1), StandardCharsets.UTF_8);
            if (name.isEmpty() || fields.putIfAbsent(name, value) != null) {
                throw new IllegalArgumentException("OMG query response field is duplicate or empty");
            }
        }
        if (fields.isEmpty()) {
            throw new IllegalArgumentException("OMG query response has no fields");
        }
        return Collections.unmodifiableMap(fields);
    }
}
