from django.db.models.signals import post_save
from django.dispatch import receiver
from saas_base.models import get_tenant_model
from saas_base.models import Group, Member, UserEmail

Tenant = get_tenant_model()


@receiver(post_save, sender=Tenant)
def ensure_owner_is_member(sender, instance: Tenant, *args, **kwargs):
    Member.objects.get_or_create(
        tenant=instance,
        user_id=instance.owner_id,
        defaults={'role': 'OWNER'},
    )


def setup():
    print('Setup Group, Member, UserEmail cache invalidation')
    Group.objects.setup_related_cache_invalidation()
    Member.objects.setup_related_cache_invalidation()
    UserEmail.objects.setup_related_cache_invalidation()

    print('Setup default permissions')
    __import__('saas_base.registry.default_perms')
