from django.utils import timezone
from saas_base.test import SaasTestCase
from saas_base.models import Member, Group, get_tenant_model


Tenant = get_tenant_model()


class TestUserSecrets(SaasTestCase):
    user_id = SaasTestCase.OWNER_USER_ID

    def test_update_foreign_key(self):
        member = Member.objects.get_from_cache_by_natural_key(self.tenant_id, self.user_id)
        self.assertEqual(member.user.username, 'demo-1')

        user = self.get_user()
        user.username = 'changed-1'
        user.save()

        member = Member.objects.get_from_cache_by_natural_key(self.tenant_id, self.user_id)
        self.assertEqual(member.user.username, 'changed-1')

    def test_update_m2m(self):
        member = Member.objects.get_from_cache_by_natural_key(self.tenant_id, self.user_id)
        perms = member.get_all_permissions()
        self.assertEqual(perms, {'*'})

        group = Group.objects.create(tenant_id=self.tenant_id, name='Admin', permissions=['org.info.view'])
        member.groups.add(group)

        member = Member.objects.get_from_cache_by_natural_key(self.tenant_id, self.user_id)
        perms = member.get_all_permissions()
        self.assertEqual(perms, {'*', 'org.info.view'})

    def test_update_field(self):
        tenant = Tenant.objects.get_from_cache_by_pk(self.tenant_id)
        tenant.name = 'Changed'
        self.assertEqual(tenant.name, 'Changed')

        tenant = Tenant.objects.get_from_cache_by_pk(self.tenant_id)
        self.assertIsNone(tenant.expires_at)
        self.assertNotEqual(tenant.name, 'Changed')

        tenant.name = 'Changed'
        tenant.expires_at = timezone.now()
        tenant.save()

        tenant = Tenant.objects.get_from_cache_by_pk(self.tenant_id)
        self.assertEqual(tenant.name, 'Changed')
        self.assertIsNotNone(tenant.expires_at)
