# SGL/sso.py
from gestion_employe.models import Employe, 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 SIRHClient(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=user_data_copy.get("departement", ""))[0]

        Employe.objects.update_or_create(
            user = user,
            defaults = {
                "departement": departement,
                "chef": 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