package hbank

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Callback is what HBank POSTs to a payment's callback URL right before charging the customer. HBank charges only
// if you answer 200 with {"resume": true} as application/json within 10 seconds.
//
// It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback
// URLs) before you approve, with VerifySignature or SignedCallbackHandler. Also check that ID and Amount match an order
// you created, and confirm with GetPayment before handing out goods.
type Callback struct {
	ID          int64       `json:"id"`
	Amount      json.Number `json:"amount"`
	Currency    string      `json:"currency"`
	Status      string      `json:"status"`
	Description string      `json:"description"`
}

// CallbackAnswer is the JSON answer to a callback.
type CallbackAnswer struct {
	Resume bool   `json:"resume"`
	Error  string `json:"error,omitempty"`
}

// Approve lets HBank charge the customer.
func Approve() CallbackAnswer { return CallbackAnswer{Resume: true} }

// Refuse refuses the payment; the customer sees message (may be "").
func Refuse(message string) CallbackAnswer { return CallbackAnswer{Resume: false, Error: message} }

// ParseCallback reads a callback request body. It returns an *Error with Code "invalid_callback" if it isn't one.
func ParseCallback(body io.Reader) (*Callback, error) {
	dec := json.NewDecoder(io.LimitReader(body, 1<<20))
	dec.UseNumber()
	var cb Callback
	if err := dec.Decode(&cb); err != nil {
		return nil, &Error{Code: "invalid_callback", Message: err.Error(), Err: err}
	}
	if cb.ID <= 0 || cb.Amount == "" || cb.Currency == "" {
		return nil, &Error{Code: "invalid_callback", Message: "missing id, amount or currency"}
	}
	return &cb, nil
}

// SignatureTolerance is how old a callback's signature may be.
const SignatureTolerance = 5 * time.Minute

// VerifySignature reports whether header (the request's HBank-Signature: "t=<unix time>,v1=<hex>") signs body (the raw
// request body, exactly as received) with secret, and was made within SignatureTolerance of now.
func VerifySignature(secret, header string, body []byte, now time.Time) bool {
	if secret == "" || header == "" {
		return false
	}
	var t, v1 string
	for _, part := range strings.Split(header, ",") {
		if k, v, ok := strings.Cut(part, "="); ok {
			switch k {
			case "t":
				t = v
			case "v1":
				v1 = v
			}
		}
	}
	ts, err := strconv.ParseInt(t, 10, 64)
	if err != nil {
		return false
	}
	if d := now.Sub(time.Unix(ts, 0)); d > SignatureTolerance || d < -SignatureTolerance {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(body)
	return hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(v1))
}

// SignedCallbackHandler is CallbackHandler that first checks the HBank-Signature with your signing secret: a callback
// without a valid one is refused ("Invalid callback") before decide is called.
func SignedCallbackHandler(secret string, decide func(r *http.Request, cb *Callback) (CallbackAnswer, error)) http.Handler {
	inner := CallbackHandler(decide)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
		if err != nil || !VerifySignature(secret, r.Header.Get("HBank-Signature"), body, time.Now()) {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			_ = json.NewEncoder(w).Encode(Refuse("Invalid callback"))
			return
		}
		r.Body = io.NopCloser(bytes.NewReader(body))
		inner.ServeHTTP(w, r)
	})
}

// CallbackHandler returns an http.Handler for your callback URL; works with net/http, chi, gorilla/mux, and Gin or
// Echo via their WrapH helpers. decide returns the answer; an error refuses the payment with a generic message.
//
//	mux.Handle("POST /hbank/callback", hbank.CallbackHandler(func(r *http.Request, cb *hbank.Callback) (hbank.CallbackAnswer, error) {
//		order, err := orders.ByTransaction(r.Context(), cb.ID)
//		if err != nil || order.Total != cb.Amount.String() {
//			return hbank.Refuse("This order is no longer available"), err
//		}
//		return hbank.Approve(), nil
//	}))
func CallbackHandler(decide func(r *http.Request, cb *Callback) (CallbackAnswer, error)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		answer := Refuse("Invalid callback")
		if cb, err := ParseCallback(r.Body); err == nil {
			if a, err := decide(r, cb); err != nil {
				answer = Refuse("The shop couldn't confirm this order")
			} else {
				answer = a
			}
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(answer)
	})
}
