package webhooks

import (
	"io"
	"net/http"
	"os"

	"github.com/labstack/echo/v4"
	"github.com/stripe/stripe-go/v81"
	"github.com/stripe/stripe-go/v81/webhook"
)

func StripeWebhook(c echo.Context) error {
	body, err := io.ReadAll(c.Request().Body)
	if err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{"error": "failed to read body"})
	}

	event, err := webhook.ConstructEvent(body, c.Request().Header.Get("Stripe-Signature"), os.Getenv("STRIPE_WEBHOOK_SECRET"))
	if err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
	}

	stripe.Key = os.Getenv("STRIPE_SECRET_KEY")

	switch event.Type {
	case "checkout.session.completed":
		// TODO: provision access for the customer
	case "customer.subscription.deleted":
		// TODO: revoke access for the customer
	}

	return c.JSON(http.StatusOK, map[string]bool{"received": true})
}
