from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.contrib.auth import get_user_model
from allauth.account.adapter import DefaultAccountAdapter
from allauth.mfa.adapter import DefaultMFAAdapter
from django_core_micha.auth.security import set_security_level
import logging

logger = logging.getLogger(__name__)

class InvitationOnlySocialAdapter(DefaultSocialAccountAdapter):
    def is_open_for_signup(self, request, sociallogin):
        User = get_user_model()
        email = sociallogin.user.email
        # Allows login only if user already exists
        return User.objects.filter(email__iexact=email).exists()

class CoreAccountAdapter(DefaultAccountAdapter):
    def login(self, request, user):
        response = super().login(request, user)
        
        if request.resolver_match:
            view_name = request.resolver_match.view_name 
            logger.debug(f"Login via View-Name: {view_name}")

            # Check for WebAuthn/Passkey Login context
            if "webauthn" in view_name and ("login" in view_name or "authenticate" in view_name):
                set_security_level(request, "strong")
            else:
                set_security_level(request, "basic")
        
        return response

class CoreMFAAdapter(DefaultMFAAdapter):
    def on_authentication_success(self, request, user, **kwargs):
        # Successful MFA implies strong session security
        if getattr(request, "user", None) and request.user.is_authenticated:
            set_security_level(request, "strong")
        return super().on_authentication_success(request, user, **kwargs)