from mozilla_django_oidc.auth import OIDCAuthenticationBackend
from django.contrib.auth.models import Group

class CustomOIDCBackend(OIDCAuthenticationBackend):
    """
    Custom authentication backend for OIDC.
    - Ensures users are created/updated from OIDC claims
    - Maps 'groups' claim from IdP into Django Groups
    """

    def create_user(self, claims):
        user = super().create_user(claims)
        user.email = claims.get("email", "")
        user.is_sso_user = True
        user.save()
        self._update_groups(user, claims)
        return user

    def update_user(self, user, claims):
        user.email = claims.get("email", user.email)
        self._update_groups(user, claims)
        user.save()
        return user

    def _update_groups(self, user, claims):
        """
        Synchronize groups from IdP claims to Django Groups.
        """
        groups = claims.get("groups", [])
        for g in groups:
            group, _ = Group.objects.get_or_create(name=g)
            user.groups.add(group)
