from django.db.models.signals import post_save

from localshop.apps.accounts.models import Team, TeamMember, User


def add_to_default_team(sender, **kwargs):
    """
    Если у нас в базе только одна команда, то автоматически
    добавляем нового пользователя в эту команду
    """
    created = kwargs.get('created')
    instance = kwargs.get('instance')

    if created:
        try:
            team = Team.objects.get()
        except (Team.DoesNotExist, Team.MultipleObjectsReturned):
            return

        TeamMember.objects.create(
            team=team,
            user=instance,
            role='developer',
        )


post_save.connect(add_to_default_team, sender=User)
