from django.test import TestCase
from django.contrib.auth import get_user_model
from django.test import Client
from accrete import models

User = get_user_model()


class MiddlewareTestCase(TestCase):

    def setUp(self):
        self.user = User(email='test@user.test', username='Test User')
        self.user.save()

    def test_no_tenant(self):
        c = Client()
        c.force_login(self.user)
        res = c.get('/')
        self.assertEqual(res.headers['X-TENANT-ID'], '0')
        self.assertFalse(res.wsgi_request.tenant)

    def test_get_non_existing(self):
        c = Client()
        c.force_login(self.user)
        res = c.get('/', {'tenant_id': 1})
        self.assertEqual(res.headers.get('X-TENANT-ID', '0'), '0')
        self.assertFalse(res.wsgi_request.tenant)
    
    def test_get_no_member(self):
        tenant = models.Tenant(name='Test Tenant')
        tenant.save()
        c = Client()
        c.force_login(self.user)
        res = c.get('/', {'tenant_id': tenant.pk + 1})
        self.assertEqual(res.headers['X-TENANT-ID'], '0')
        self.assertFalse(res.wsgi_request.tenant)
        self.assertFalse(res.wsgi_request.member)

    def test_get(self):
        tenant = models.Tenant(name='Test Tenant')
        tenant.save()
        member = models.Member(
            tenant=tenant,
            user=self.user
        )
        member.save()
        c = Client()
        c.force_login(self.user)
        res = c.get('/')
        self.assertEqual(res.headers['X-TENANT-ID'], str(tenant.pk))
        self.assertEqual(res.wsgi_request.tenant, tenant)
        self.assertEqual(res.wsgi_request.member, member)

    def test_post_no_member(self):
        c = Client()
        c.force_login(self.user)
        res = c.post('/', {'tenant_id': 1})
        self.assertEqual(res.headers.get('X-TENANT-ID', '0'), '0')

    def test_post(self):
        tenant = models.Tenant(name='Test Tenant')
        tenant.save()
        member = models.Member(
            tenant=tenant,
            user=self.user
        )
        member.save()
        c = Client()
        c.force_login(self.user)
        res = c.post('/', {'tenant_id': tenant.pk})
        self.assertEqual(res.headers['X-TENANT-ID'], str(tenant.pk))
