"""Stripe Checkout and Customer Portal session management."""

from __future__ import annotations

import stripe

from billing.config import get_config
from billing.models import CheckoutSession


def create_checkout(
    user_id: str,
    plan: str,
    email: str | None = None,
) -> CheckoutSession:
    """Create a Stripe Checkout session for the given plan.

    Args:
        user_id: Internal user identifier, stored as client_reference_id.
        plan: Plan name as defined in BillingConfig.product_plans.
        email: Optional customer email to pre-fill in checkout.

    Returns:
        CheckoutSession with the redirect URL and session ID.

    Raises:
        ValueError: If the plan name is not found in configured plans.
        stripe.StripeError: On Stripe API failures.
    """
    config = get_config()

    price_id = config.product_plans.get(plan)
    if not price_id:
        available = ", ".join(config.product_plans.keys())
        raise ValueError(f"Unknown plan '{plan}'. Available plans: {available}")

    params: dict = {
        "mode": "subscription",
        "line_items": [{"price": price_id, "quantity": 1}],
        "success_url": config.success_url,
        "cancel_url": config.cancel_url,
        "client_reference_id": user_id,
        "metadata": {"user_id": user_id, "plan": plan},
    }

    if email:
        params["customer_email"] = email

    session = stripe.checkout.Session.create(**params)

    return CheckoutSession(
        url=session.url,
        session_id=session.id,
    )


def create_portal_session(customer_id: str) -> str:
    """Create a Stripe Customer Portal session.

    Args:
        customer_id: Stripe customer ID.

    Returns:
        The portal session URL for redirect.

    Raises:
        stripe.StripeError: On Stripe API failures.
    """
    session = stripe.billing_portal.Session.create(
        customer=customer_id,
        return_url=get_config().success_url,
    )
    return session.url
