import os
import stripe
from fastapi import APIRouter, Header, HTTPException, Request, status

router = APIRouter(prefix="/webhooks")
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
_webhook_secret = os.environ["STRIPE_WEBHOOK_SECRET"]


@router.post("/stripe")
async def stripe_webhook(request: Request, stripe_signature: str = Header(None)):
    body = await request.body()
    try:
        event = stripe.Webhook.construct_event(body, stripe_signature, _webhook_secret)
    except stripe.SignatureVerificationError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid signature") from exc

    if event["type"] == "checkout.session.completed":
        pass  # TODO: provision access for the customer
    elif event["type"] == "customer.subscription.deleted":
        pass  # TODO: revoke access for the customer

    return {"received": True}
