"""Syncs first/last name from SSO provider on every InvenTree login"""

from plugin import InvenTreePlugin

from . import PLUGIN_VERSION


class SSONameSync(InvenTreePlugin):

    """SSONameSync - custom InvenTree plugin."""

    # Plugin metadata
    TITLE = "SSONameSync"
    NAME = "SSONameSync"
    SLUG = "ssonamesync"
    DESCRIPTION = "Syncs first/last name from SSO provider on every InvenTree login"
    VERSION = PLUGIN_VERSION

    # Additional project information
    AUTHOR = "hillsandales"
    WEBSITE = "https://github.com/hillsandales/inventree-sso-name-sync"
    LICENSE = "MIT"

    # Optionally specify supported InvenTree versions
    # MIN_VERSION = '0.18.0'
    # MAX_VERSION = '2.0.0'


# Wire up the signal outside the class so it loads on import
from allauth.socialaccount.signals import social_account_updated
from django.dispatch import receiver

@receiver(social_account_updated)
def sync_name_from_sso(sender, request, sociallogin, **kwargs):
    extra = sociallogin.account.extra_data

    # Newer allauth (65.15+): claims are nested under "userinfo" or "id_token"
    # Older allauth: claims are at the root
    claims = extra.get("userinfo") or extra.get("id_token") or extra

    first = claims.get("given_name", "")
    last = claims.get("family_name", "")

    if first or last:
        user = sociallogin.user
        user.first_name = first
        user.last_name = last
        user.save(update_fields=["first_name", "last_name"])
