"""
FAB Club Social Auth Pipeline

python-social-auth runs a configurable pipeline after each successful
OAuth login. Add SOCIAL_AUTH_PIPELINE to your settings to use these steps.

Recommended pipeline order (append after the defaults):
    SOCIAL_AUTH_PIPELINE = (
        'social_core.pipeline.social_auth.social_details',
        'social_core.pipeline.social_auth.social_uid',
        'social_core.pipeline.social_auth.social_user',
        'social_core.pipeline.user.get_username',
        'social_core.pipeline.user.create_user',
        'social_core.pipeline.social_auth.associate_user',
        'social_core.pipeline.social_auth.load_extra_data',
        'social_core.pipeline.user.user_details',
        # FAB-specific steps below:
        'apps.fab_auth.pipeline.save_fab_profile',
        'apps.fab_auth.pipeline.attach_tenant_user',
    )
"""
import logging
from django.utils import timezone

logger = logging.getLogger(__name__)


def save_fab_profile(strategy, details, backend, user=None, *args, **kwargs):
    """
    After login/registration, persist FAB Club data to the user's profile.
    Stores fab_number, tier, and points in the user's profile if a profile
    model exists, otherwise caches in session for the view layer.
    """
    if user is None:
        return

    fab_number = details.get('fab_number')
    fab_tier   = details.get('fab_tier')
    fab_points = details.get('fab_points', 0)
    fab_wallet = details.get('fab_wallet_pence', 0)

    # Cache in session so templates can display without a DB hit
    strategy.session_set('fab_number',   fab_number)
    strategy.session_set('fab_tier',     fab_tier)
    strategy.session_set('fab_points',   fab_points)
    strategy.session_set('fab_wallet',   fab_wallet)
    strategy.session_set('fab_login_at', str(timezone.now()))

    # If user has a profile model with these fields, update it
    try:
        profile = user.profile
        changed = False
        if fab_number and getattr(profile, 'fab_number', None) != fab_number:
            profile.fab_number = fab_number
            changed = True
        if fab_tier and getattr(profile, 'fab_tier', None) != fab_tier:
            profile.fab_tier = fab_tier
            changed = True
        if changed:
            profile.save()
    except Exception:
        pass  # No profile model — that's fine

    logger.info(
        'FAB Club login: user=%s fab_number=%s tier=%s',
        user.pk, fab_number, fab_tier
    )


def attach_tenant_user(strategy, backend, user=None, request=None, *args, **kwargs):
    """
    After a successful FAB Club OAuth login, ensure the user is attached
    to the current tenant (request.tenant) as a TenantUser.

    If the tenant already has this user, just update their last_login.
    """
    if user is None or request is None:
        return

    tenant = getattr(request, 'tenant', None)
    if tenant is None or getattr(tenant, 'pk', 0) == 0:
        return

    try:
        from apps.tenants.models import TenantUser
        TenantUser.objects.get_or_create(
            tenant=tenant,
            user=user,
            defaults={'role': 'viewer', 'is_active': True},
        )
    except Exception as e:
        logger.warning('attach_tenant_user failed: %s', e)
