// Package flowpay verifies FlowPayra Lite webhook and return-URL signatures (standard library only).
//
//	http.HandleFunc("/flowpay/webhook", func(w http.ResponseWriter, r *http.Request) {
//		body, _ := io.ReadAll(r.Body) // the raw body, before any JSON decoding
//		if !flowpay.VerifyWebhook(secret, r.Header.Get("FlowPay-Signature"), body, time.Now(), 5*time.Minute) {
//			http.Error(w, "bad signature", http.StatusBadRequest)
//			return
//		}
//		// … handle the event idempotently by its id, then answer 2xx
//	})
//
//	// Return page: show the outcome; fulfil from the webhook or GET /v1/orders/{id}.
//	orderID, status, ok := flowpay.VerifyReturnURL(secret, r.URL.String(), time.Now(), 10*time.Minute)
package flowpay

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"net/url"
	"strconv"
	"strings"
	"time"
)

func mac(secret string, data []byte) []byte {
	m := hmac.New(sha256.New, []byte(secret))
	m.Write(data)
	return m.Sum(nil)
}

// VerifyWebhook checks `FlowPay-Signature: t=<unix seconds>,v1=<hex>` over "<t>.<raw body>"; any v1 may match
// (secret rotation) and t must be within tolerance of now.
func VerifyWebhook(secret, header string, rawBody []byte, now time.Time, tolerance time.Duration) bool {
	if secret == "" || header == "" {
		return false
	}
	ts := int64(-1)
	var sigs [][]byte
	for _, part := range strings.Split(header, ",") {
		k, v, found := strings.Cut(strings.TrimSpace(part), "=")
		if !found {
			continue
		}
		switch k {
		case "t":
			if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 0 {
				ts = n
			}
		case "v1":
			s, err := hex.DecodeString(v)
			if err != nil {
				return false
			}
			sigs = append(sigs, s)
		}
	}
	if ts < 0 || len(sigs) == 0 {
		return false
	}
	if d := now.Unix() - ts; d > int64(tolerance/time.Second) || -d > int64(tolerance/time.Second) {
		return false
	}
	expected := mac(secret, append([]byte(strconv.FormatInt(ts, 10)+"."), rawBody...))
	for _, s := range sigs {
		if hmac.Equal(s, expected) {
			return true
		}
	}
	return false
}

// VerifyReturnURL checks sig = hex(HMAC-SHA256(secret, "<order_id>.<status>.<ts>")) over the last occurrence of
// each parameter the checkout appended, and ts within maxAge of now.
func VerifyReturnURL(secret, rawURL string, now time.Time, maxAge time.Duration) (orderID, status string, ok bool) {
	u, err := url.Parse(rawURL)
	if err != nil || secret == "" {
		return "", "", false
	}
	q := u.Query()
	last := func(k string) string {
		if v := q[k]; len(v) > 0 {
			return v[len(v)-1]
		}
		return ""
	}
	orderID, status, tsText, sigText := last("order_id"), last("status"), last("ts"), last("sig")
	ts, err := strconv.ParseInt(tsText, 10, 64)
	if orderID == "" || status == "" || err != nil || ts < 0 || len(sigText) != 64 {
		return "", "", false
	}
	if d := now.Unix() - ts; d > int64(maxAge/time.Second) || -d > int64(maxAge/time.Second) {
		return "", "", false
	}
	sig, err := hex.DecodeString(sigText)
	if err != nil || !hmac.Equal(sig, mac(secret, []byte(orderID+"."+status+"."+tsText))) {
		return "", "", false
	}
	return orderID, status, true
}
