// PayVAN request signing and webhook verification (Go 1.21+, standard library only).
//
// Run `go run payvan_sign.go` to check it against the reference vectors from
// https://docs.payvan.net/#auth-reference. To use it, copy SignRequest and
// VerifyWebhook into your own package.
package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
)

// SignRequest returns the four authentication headers for one API request.
// path includes the query string, if any. body must be the exact bytes you
// send: sign first, then send the same bytes without re-encoding. Pass an
// empty requestID and a zero timestamp to get fresh ones.
func SignRequest(secret, method, path, shopID string, body []byte, requestID string, timestamp int64) map[string]string {
	if requestID == "" {
		requestID = uuid4()
	}
	if timestamp == 0 {
		timestamp = time.Now().Unix()
	}
	message := strings.Join([]string{
		"v1", strings.ToUpper(method), path, shopID, requestID,
		strconv.FormatInt(timestamp, 10), sha256hex(body),
	}, "\n")
	return map[string]string{
		"X-SHOP-ID":           shopID,
		"X-REQUEST-ID":        requestID,
		"X-REQUEST-TIMESTAMP": strconv.FormatInt(timestamp, 10),
		"X-REQUEST-SIGNATURE": "v1=" + hmacHex(secret, message),
	}
}

// VerifyWebhook checks a webhook from PayVAN. secrets is every key you
// currently hold (two during a key rotation). url is the full notification URL
// PayVAN posted to, exactly as configured. header is the request's header:
// http.Header looks names up case-insensitively, so pass r.Header as is.
func VerifyWebhook(secrets []string, url string, header interface{ Get(string) string }, body []byte, maxAge time.Duration) bool {
	timestamp, err := strconv.ParseInt(header.Get("X-WEBHOOK-TIMESTAMP"), 10, 64)
	if err != nil {
		return false
	}
	message := strings.Join([]string{
		"v1-webhook", "POST", url, header.Get("X-SHOP-ID"), header.Get("X-WEBHOOK-ID"),
		strconv.FormatInt(timestamp, 10), sha256hex(body),
	}, "\n")

	// The header may carry several signatures: "v1-webhook=<a>,v1-webhook=<b>".
	var received []string
	for _, part := range strings.Split(header.Get("X-WEBHOOK-SIGNATURE"), ",") {
		label, value, _ := strings.Cut(strings.TrimSpace(part), "=")
		if label == "v1-webhook" && value != "" {
			received = append(received, strings.TrimSpace(value))
		}
	}

	ok := false
	for _, secret := range secrets {
		expected := []byte(hmacHex(secret, message))
		for _, sig := range received {
			ok = hmac.Equal(expected, []byte(sig)) || ok
		}
	}
	age := time.Since(time.Unix(timestamp, 0))
	return ok && age < maxAge && age > -maxAge
}

func sha256hex(b []byte) string {
	sum := sha256.Sum256(b)
	return hex.EncodeToString(sum[:])
}

func hmacHex(key, message string) string {
	m := hmac.New(sha256.New, []byte(key))
	m.Write([]byte(message))
	return hex.EncodeToString(m.Sum(nil))
}

func uuid4() string {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		panic(err)
	}
	b[6] = b[6]&0x0f | 0x40
	b[8] = b[8]&0x3f | 0x80
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}

// headerMap is a plain map with case-insensitive lookup, for the self-test.
type headerMap map[string]string

func (h headerMap) Get(name string) string {
	for k, v := range h {
		if strings.EqualFold(k, name) {
			return v
		}
	}
	return ""
}

func main() {
	const secret = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"

	body := []byte(`{"OrderId":"A-1001","Amount":"1499.00","Currency":"USD"}`)
	headers := SignRequest(secret, "POST", "/v1/payments", "1001", body,
		"2f0f2b1c-6c4b-4a1e-9a3d-8b7f0c5e1d42", 1789732800)
	if got, want := headers["X-REQUEST-SIGNATURE"], "v1=429303de742eaefaa085170c872d03d4d9f40ca3457c5507dab76ebaadb6bfda"; got != want {
		fmt.Fprintf(os.Stderr, "request signature: FAIL\n got  %s\n want %s\n", got, want)
		os.Exit(1)
	}
	fmt.Println("request signature: OK")

	hook := []byte(`{"Event":"Payment","TransactionId":"3554","OrderId":"A-1001","Amount":"1499.00","Currency":"USD"}`)
	hookHeaders := headerMap{
		"X-SHOP-ID":           "1001",
		"X-WEBHOOK-ID":        "wh_7f3a9c",
		"X-WEBHOOK-TIMESTAMP": "1789732860",
		"X-WEBHOOK-SIGNATURE": "v1-webhook=8d1f0f9a2207241e640bd28aef00de33aca990e7087b06df38a09917d995b4b6",
	}
	// maxAge is disabled here only because the vector has a fixed timestamp.
	if !VerifyWebhook([]string{secret}, "https://shop.example/hooks/payvan", hookHeaders, hook, 1<<62) {
		fmt.Fprintln(os.Stderr, "webhook signature: FAIL")
		os.Exit(1)
	}
	fmt.Println("webhook signature: OK")
}
