"""
django_stripe_billing settings.

All settings are accessed via the `stripe_billing_settings` helper, which reads
from Django settings with sensible defaults.  Example project settings::

    STRIPE_BILLING = {
        'STRIPE_SECRET_KEY': env('STRIPE_SECRET_KEY'),
        'STRIPE_WEBHOOK_SECRET': env('STRIPE_WEBHOOK_SECRET'),
        'STRIPE_MODE': 'live',          # 'live' or 'test'
        'ENVIRONMENT': env('ENVIRONMENT', default='production'),
        'APP_TITLE': 'My SaaS',
        'APP_DOMAIN': 'https://myapp.com',
        'SUPPORT_EMAIL': 'support@myapp.com',
        'EMAIL_SUBJECT_PREFIX': '[My SaaS]',
        # Optional: outgoing Zapier/Make/n8n webhooks keyed by Stripe event type
        'OUTGOING_WEBHOOK_URLS': {
            'invoice.payment_succeeded': '',
            'invoice.payment_failed': '',
            'customer.subscription.deleted': '',
        },
    }
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

DEFAULTS = {
    'STRIPE_SECRET_KEY': '',
    'STRIPE_WEBHOOK_SECRET': '',
    'STRIPE_MODE': 'live',
    'ENVIRONMENT': 'production',
    'APP_TITLE': 'My App',
    'APP_DOMAIN': 'http://localhost:8000',
    'SUPPORT_EMAIL': 'support@example.com',
    'EMAIL_SUBJECT_PREFIX': '[Billing]',
    'OUTGOING_WEBHOOK_URLS': {},
    # Celery task queue. Set to None to use the default queue.
    'CELERY_QUEUE': None,
}


def require_stripe_secret_key() -> str:
    """
    Return STRIPE_SECRET_KEY; raise ImproperlyConfigured if empty.

    Use at boundaries (checkout, portal) so missing config fails fast with
    a clear message instead of a Stripe API error.
    """
    key = stripe_billing_settings.STRIPE_SECRET_KEY
    if not (key and key.strip()):
        raise ImproperlyConfigured(
            'STRIPE_SECRET_KEY is required for Stripe API calls. '
            'Set it in STRIPE_BILLING or as top-level STRIPE_SECRET_KEY.'
        )
    return key.strip()


def require_webhook_secret() -> str:
    """
    Return STRIPE_WEBHOOK_SECRET; raise ImproperlyConfigured if empty.

    Use in the webhook view so signature verification does not run with
    an empty secret.
    """
    secret = stripe_billing_settings.STRIPE_WEBHOOK_SECRET
    if not (secret and secret.strip()):
        raise ImproperlyConfigured(
            'STRIPE_WEBHOOK_SECRET is required for webhook verification. '
            'Set it in STRIPE_BILLING or as top-level STRIPE_WEBHOOK_SECRET.'
        )
    return secret.strip()


class _Settings:
    """Lazy accessor for STRIPE_BILLING dict in Django settings."""

    def __getattr__(self, name):
        if name not in DEFAULTS:
            raise AttributeError(f'Unknown django_stripe_billing setting: {name!r}')
        user_settings = getattr(settings, 'STRIPE_BILLING', {})
        # Fall back to legacy top-level settings for zero-config migration
        legacy = {
            'STRIPE_SECRET_KEY': getattr(settings, 'STRIPE_SECRET_KEY', ''),
            'STRIPE_WEBHOOK_SECRET': getattr(
                settings, 'STRIPE_WEBHOOK_SECRET', ''
            ),
            'STRIPE_MODE': getattr(settings, 'STRIPE_MODE', 'live'),
            'ENVIRONMENT': getattr(settings, 'ENVIRONMENT', 'production'),
            'APP_TITLE': getattr(settings, 'APP_TITLE', ''),
            'APP_DOMAIN': getattr(
                settings, 'REDIRECT_DOMAIN', 'http://localhost:8000'
            ),
            'SUPPORT_EMAIL': getattr(
                settings, 'SUPPORT_EMAIL', 'support@example.com'
            ),
            'EMAIL_SUBJECT_PREFIX': getattr(
                settings, 'EMAIL_SUBJECT_PREFIX', '[Billing]'
            ),
            'OUTGOING_WEBHOOK_URLS': getattr(
                settings, 'OUTGOING_WEBHOOK_URLS', {}
            ),
        }
        # Priority: STRIPE_BILLING dict > legacy top-level > hard defaults
        return user_settings.get(name, legacy.get(name, DEFAULTS[name]))


stripe_billing_settings = _Settings()
