"""
Payment Routes - Stripe integration endpoints.
"""

from fastapi import APIRouter, HTTPException, Request
from typing import Dict
from pydantic import BaseModel
import structlog

from app.payments.stripe_service import StripeService

logger = structlog.get_logger(__name__)

router = APIRouter()
stripe_service = StripeService()


class CheckoutRequest(BaseModel):
    """Checkout session request."""
    tier: str  # 'pro' or 'enterprise'
    period: str  # 'monthly', 'annual', or 'lifetime'
    email: str
    success_url: str
    cancel_url: str


class CheckoutResponse(BaseModel):
    """Checkout session response."""
    session_id: str
    url: str
    amount: int
    currency: str


@router.post("/checkout", response_model=CheckoutResponse)
async def create_checkout_session(request: CheckoutRequest):
    """
    Create Stripe Checkout session.
    
    Example:
    ```json
    {
        "tier": "pro",
        "period": "monthly",
        "email": "user@example.com",
        "success_url": "http://localhost:3000/success",
        "cancel_url": "http://localhost:3000/cancel"
    }
    ```
    """
    logger.info("checkout_request",
        tier=request.tier,
        period=request.period,
        email=request.email)
    
    try:
        session_data = stripe_service.create_checkout_session(
            tier=request.tier,
            period=request.period,
            customer_email=request.email,
            success_url=request.success_url,
            cancel_url=request.cancel_url
        )
        
        return CheckoutResponse(**session_data)
    
    except Exception as e:
        logger.error("checkout_error", error=str(e))
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/webhook")
async def stripe_webhook(request: Request):
    """
    Handle Stripe webhook events.
    
    This endpoint is called by Stripe when events occur
    (successful payment, subscription cancelled, etc.)
    """
    payload = await request.body()
    sig_header = request.headers.get('stripe-signature')
    
    if not sig_header:
        raise HTTPException(status_code=400, detail="Missing signature")
    
    try:
        result = stripe_service.handle_webhook(payload, sig_header)
        
        logger.info("webhook_processed", result=result)
        
        return {"status": "success", "result": result}
    
    except Exception as e:
        logger.error("webhook_error", error=str(e))
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/subscription/{email}")
async def get_subscription(email: str):
    """Get subscription information for a customer."""
    logger.info("subscription_request", email=email)
    
    try:
        subscription_info = stripe_service.get_subscription_info(email)
        
        if not subscription_info:
            raise HTTPException(status_code=404, detail="No subscription found")
        
        return subscription_info
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error("subscription_error", error=str(e))
        raise HTTPException(status_code=500, detail=str(e))
