# notcloudapp/pipeline.py
from django.contrib.auth.models import User
from django.shortcuts import redirect
from social_core.exceptions import AuthAlreadyAssociated,AuthForbidden
from .models import Profile
import logging

logger = logging.getLogger(__name__)

def social_user_graceful(backend, uid, user=None, *args, **kwargs):
    """
    Gracefully handle already associated social accounts.
    If account is associated with another user, link to current session user instead.
    """
    provider = backend.name
    social = backend.strategy.storage.user.get_social_auth(provider, uid)
    
    if social:
        if user and social.user != user:
            # Social account already associated with another user
            if user.is_authenticated:
                # If current user is authenticated, reassociate to them
                logger.info(f"Reassociating {provider} account from user {social.user.id} to {user.id}")
                social.user = user
                social.save()
                return {'social': social, 'user': user, 'is_new': False}
            else:
                # If no user is authenticated, use the associated user
                return {'social': social, 'user': social.user, 'is_new': False}
        elif not user:
            user = social.user
            
    return {'social': social, 'user': user, 'is_new': user is None}

def create_user_profile(backend, user, response, *args, **kwargs):
    """
    Create or update user profile for social auth users
    """
    if user:
        try:
            profile, created = Profile.objects.get_or_create(
                user=user,
                defaults={
                    'email': user.email,
                    'agreed_to_terms': True  # Social auth implies agreement
                }
            )
            
            # Update email if it changed
            if profile.email != user.email:
                profile.email = user.email
                profile.save()
                
            logger.info(f"{'Created' if created else 'Updated'} profile for user {user.email}")
            
        except Exception as e:
            logger.error(f"Error creating/updating profile for {user.email}: {e}")

def check_email_verified(backend, details, response, *args, **kwargs):
    """
    Ensure email is verified before allowing login
    """
    if backend.name == 'google-oauth2':
        if not response.get('email_verified', False):
            raise AuthForbidden(backend, 'Email not verified')
    
    return {'details': details}