// FlowPayra Lite webhook and return-URL signature verification for Java 11+, JDK only.
//
//   // Webhook endpoint (e.g. Spring): verify the raw body bytes, before any JSON mapping.
//   @PostMapping("/flowpay/webhook")
//   ResponseEntity<Void> webhook(@RequestHeader("FlowPay-Signature") String sig, @RequestBody byte[] body) {
//       if (!FlowPay.verifyWebhook(secret, sig, body, Instant.now().getEpochSecond(), 300)) return ResponseEntity.badRequest().build();
//       // ... handle the event idempotently by its id
//       return ResponseEntity.ok().build();
//   }
//
//   // Return page: show the outcome; fulfil from the webhook or GET /v1/orders/{id}.
//   Optional<FlowPay.Return> r = FlowPay.verifyReturnUrl(secret, fullRequestUrl, Instant.now().getEpochSecond(), 600);

import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class FlowPay {
    private FlowPay() {}

    /** A verified return: the order and its status. */
    public static final class Return {
        public final String orderId;
        public final String status;

        Return(String orderId, String status) {
            this.orderId = orderId;
            this.status = status;
        }
    }

    private static byte[] mac(String secret, byte[] data) {
        try {
            Mac m = Mac.getInstance("HmacSHA256");
            m.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return m.doFinal(data);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    private static byte[] hex(String s) {
        if (s.length() % 2 != 0) return null;
        byte[] out = new byte[s.length() / 2];
        for (int i = 0; i < out.length; i++) {
            int hi = Character.digit(s.charAt(2 * i), 16);
            int lo = Character.digit(s.charAt(2 * i + 1), 16);
            if (hi < 0 || lo < 0) return null;
            out[i] = (byte) (hi * 16 + lo);
        }
        return out;
    }

    /** {@code FlowPay-Signature: t=<unix seconds>,v1=<hex>} over "<t>.<raw body>"; any v1 may match (rotation). */
    public static boolean verifyWebhook(String secret, String header, byte[] rawBody, long now, long toleranceSecs) {
        if (secret == null || secret.isEmpty() || header == null) return false;
        Long ts = null;
        List<byte[]> sigs = new ArrayList<>();
        for (String part : header.split(",")) {
            String p = part.trim();
            int i = p.indexOf('=');
            if (i < 0) continue;
            String k = p.substring(0, i);
            String v = p.substring(i + 1);
            if (k.equals("t") && v.matches("\\d{1,18}")) {
                ts = Long.parseLong(v);
            } else if (k.equals("v1")) {
                byte[] b = hex(v);
                if (b == null) return false;
                sigs.add(b);
            }
        }
        if (ts == null || sigs.isEmpty() || Math.abs(now - ts) > toleranceSecs) return false;
        byte[] prefix = (ts + ".").getBytes(StandardCharsets.UTF_8);
        byte[] signed = new byte[prefix.length + rawBody.length];
        System.arraycopy(prefix, 0, signed, 0, prefix.length);
        System.arraycopy(rawBody, 0, signed, prefix.length, rawBody.length);
        byte[] expected = mac(secret, signed);
        for (byte[] s : sigs) {
            if (MessageDigest.isEqual(s, expected)) return true;
        }
        return false;
    }

    /** sig = hex(HMAC-SHA256(secret, "<order_id>.<status>.<ts>")) over the last occurrence of each parameter,
     *  and ts within maxAgeSecs of now. */
    public static Optional<Return> verifyReturnUrl(String secret, String url, long now, long maxAgeSecs) {
        if (secret == null || secret.isEmpty()) return Optional.empty();
        String query = URI.create(url).getRawQuery();
        Map<String, String> last = new HashMap<>();
        if (query != null) {
            for (String pair : query.split("&")) {
                int i = pair.indexOf('=');
                if (i < 0) continue;
                last.put(URLDecoder.decode(pair.substring(0, i), StandardCharsets.UTF_8),
                    URLDecoder.decode(pair.substring(i + 1), StandardCharsets.UTF_8));
            }
        }
        String orderId = last.get("order_id"), status = last.get("status"), ts = last.get("ts"), sig = last.get("sig");
        if (orderId == null || status == null || ts == null || sig == null || !ts.matches("\\d{1,18}") || sig.length() != 64) {
            return Optional.empty();
        }
        if (Math.abs(now - Long.parseLong(ts)) > maxAgeSecs) return Optional.empty();
        byte[] given = hex(sig);
        byte[] expected = mac(secret, (orderId + "." + status + "." + ts).getBytes(StandardCharsets.UTF_8));
        return given != null && MessageDigest.isEqual(given, expected) ? Optional.of(new Return(orderId, status)) : Optional.empty();
    }
}
