package handlers

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

	"github.com/labstack/echo/v4"
	"github.com/stretchr/testify/assert"
)

func TestVerifyGooglePubSubToken_MissingAuth_ReturnsFalse(t *testing.T) {
	handler := &SubscriptionWebhookHandler{enabled: true}

	e := echo.New()
	// Request with no Authorization header
	req := httptest.NewRequest(http.MethodPost, "/api/subscription/webhook/google/", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)

	result := handler.VerifyGooglePubSubToken(c)
	assert.False(t, result, "VerifyGooglePubSubToken should return false when Authorization header is missing")
}

func TestVerifyGooglePubSubToken_InvalidToken_ReturnsFalse(t *testing.T) {
	handler := &SubscriptionWebhookHandler{enabled: true}

	e := echo.New()
	req := httptest.NewRequest(http.MethodPost, "/api/subscription/webhook/google/", nil)
	req.Header.Set("Authorization", "Bearer invalid-garbage-token")
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)

	result := handler.VerifyGooglePubSubToken(c)
	assert.False(t, result, "VerifyGooglePubSubToken should return false for an invalid/unverifiable token")
}

func TestDecodeAppleSignedPayload_InvalidJWS_ReturnsError(t *testing.T) {
	handler := &SubscriptionWebhookHandler{enabled: true}

	// No signature parts
	_, err := handler.decodeAppleSignedPayload("not-a-jws")
	assert.Error(t, err, "should reject payload that is not valid JWS format")
}

func TestDecodeAppleSignedPayload_VerificationFails_ReturnsError(t *testing.T) {
	handler := &SubscriptionWebhookHandler{enabled: true}

	// Construct a JWS-shaped string with 3 parts but no valid signature.
	// The handler should now attempt verification and fail.
	// header.payload.signature -- all base64url garbage
	fakeJWS := "eyJhbGciOiJFUzI1NiJ9.eyJ0ZXN0IjoidHJ1ZSJ9.invalidsig"

	_, err := handler.decodeAppleSignedPayload(fakeJWS)
	assert.Error(t, err, "should return error when Apple signature verification fails")
}
