package middleware

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestStripeRawBodyPreservesPayloadAndSignature(t *testing.T) {
	payload := []byte("{\n  \"exact\": \"bytes\"\n}")
	req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))
	req.Header.Set("Stripe-Signature", "t=1,v1=abc")
	rr := httptest.NewRecorder()
	NewStripeRawBodyMiddleware().Handle(func(_ http.ResponseWriter, r *http.Request) {
		got, sig, ok := StripeWebhookPayload(r.Context())
		require.True(t, ok)
		require.Equal(t, payload, got)
		require.Equal(t, "t=1,v1=abc", sig)
	})(rr, req)
	require.Equal(t, http.StatusOK, rr.Code)
}

func TestStripeRawBodyRejectsOverOneMiB(t *testing.T) {
	req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(make([]byte, stripeWebhookMaxBytes+1)))
	rr := httptest.NewRecorder()
	called := false
	NewStripeRawBodyMiddleware().Handle(func(http.ResponseWriter, *http.Request) { called = true })(rr, req)
	require.False(t, called)
	require.Equal(t, http.StatusRequestEntityTooLarge, rr.Code)
}
