# SGL/sso.py
from authentification.models import Profile, Departement
from simple_sso.sso_client.client import Client
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group

User = get_user_model()

class SGLClient(Client):
    def build_user(self, user_data):
        """Crée le User et son Profile avec les infos reçues du serveur."""
        user_data_copy = user_data.copy()
        user_data.pop("departement")
        user_data.pop("chef_departement")
        user_data.pop("groups")

        user = super().build_user(user_data)
        departement = Departement.objects.get_or_create(
            nom_departement=user_data_copy.get("departement", "")
        )[0]

        Profile.objects.update_or_create(
            user=user,
            defaults={
                "departement": departement,
                "chef_departement": user_data_copy.get("chef_departement", ""),
            }
        )

        for group_name in user_data_copy.get("groups", []):
            group, _ = Group.objects.get_or_create(name=group_name)
            user.groups.add(group)

        return user
