"""
Webhook endpoints for external service integrations.

- Stripe payment webhooks
- Future: Other payment providers, notification services, etc.
"""
import logging
from fastapi import APIRouter, HTTPException, Request, Header, status

from app.database import get_db
from app.services.stripe_service import StripeService

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/stripe")
async def stripe_webhook(
    request: Request,
    stripe_signature: str = Header(None, alias="Stripe-Signature"),
):
    """
    Handle Stripe webhook events.
    
    This endpoint receives events from Stripe when:
    - Payment succeeds or fails
    - Subscription is updated or cancelled
    - Invoice is created or paid
    
    The webhook must be configured in Stripe Dashboard to point to:
    https://your-domain.com/api/webhooks/stripe
    
    Required Header:
    - Stripe-Signature: Stripe's webhook signature for verification
    """
    if not stripe_signature:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Missing Stripe-Signature header",
        )
    
    if not StripeService.is_configured():
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Stripe not configured",
        )
    
    # Get raw body for signature verification
    payload = await request.body()
    
    try:
        async for db in get_db():
            result = await StripeService.handle_webhook(
                payload=payload,
                sig_header=stripe_signature,
                db=db,
            )
            return result
            
    except ValueError as e:
        logger.error(f"Webhook validation error: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e),
        )
    except Exception as e:
        logger.error(f"Webhook processing error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Webhook processing failed",
        )

