# Copyright (C) 2018-2025 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later

from django.conf import settings


def save_user_profile(instance, created, raw, **_kwargs):
    """
    Hook to create and save a profile when an user is updated if it is not registered with the signup form
    """
    if not raw and created and instance.is_active and not hasattr(instance, "_no_signal"):
        from .models import Profile
        Profile.objects.get_or_create(user=instance)
        if instance.is_superuser:
            instance.profile.email_confirmed = True
            instance.profile.registration_valid = True
        instance.profile.save()


def update_wei_registration_fee_on_membership_creation(sender, instance, created, **kwargs):
    if not hasattr(instance, "_no_signal") and 'wei' in settings.INSTALLED_APPS and created:
        from wei.models import WEIRegistration
        if instance.club.id == 1 or instance.club.id == 2:
            registrations = WEIRegistration.objects.filter(
                user=instance.user,
                wei__year=instance.date_start.year,
            )
            for r in registrations:
                r._force_save = True
                r.save()


def update_wei_registration_fee_on_club_change(sender, instance, **kwargs):
    if not hasattr(instance, "_no_signal") and 'wei' in settings.INSTALLED_APPS and (instance.id == 1 or instance.id == 2):
        from wei.models import WEIRegistration
        registrations = WEIRegistration.objects.filter(
            wei__year=instance.membership_start.year,
        )
        for r in registrations:
            r._force_save = True
            r.save()
