from saas_base.models import Invitation
from tests.client import FixturesTestCase


class TestInvitationsAPI(FixturesTestCase):
    user_id = FixturesTestCase.OWNER_USER_ID

    def setUp(self):
        super().setUp()
        self.invitation = Invitation.objects.create(
            tenant=self.tenant,
            inviter_id=self.OWNER_USER_ID,
            email='invitee@example.com',
            role='MEMBER',
            status=Invitation.InviteStatus.SENT,
        )

    def test_list_invitations(self):
        self.force_login()
        url = f'/m/invitations/'
        resp = self.client.get(url)
        self.assertEqual(resp.status_code, 200)
        data = resp.json()
        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['id'], str(self.invitation.id))

    def test_create_invitation(self):
        self.force_login()
        url = f'/m/invitations/'
        data = {
            'email': 'new@example.com',
            'role': 'MEMBER',
        }
        resp = self.client.post(url, data)
        self.assertEqual(resp.status_code, 201)

        invitation = Invitation.objects.get(email='new@example.com')
        self.assertEqual(invitation.tenant_id, self.tenant_id)
        self.assertEqual(invitation.role, 'MEMBER')
        self.assertEqual(invitation.inviter_id, self.user_id)

    def test_update_invitation(self):
        self.force_login()
        url = f'/m/invitations/{self.invitation.id}/'
        data = {
            'role': 'ADMIN',
        }
        resp = self.client.patch(url, data)
        self.assertEqual(resp.status_code, 200)

        self.invitation.refresh_from_db()
        self.assertEqual(self.invitation.role, 'ADMIN')

    def test_delete_invitation(self):
        self.force_login()
        url = f'/m/invitations/{self.invitation.id}/'
        resp = self.client.delete(url)
        self.assertEqual(resp.status_code, 204)

        self.assertFalse(Invitation.objects.filter(id=self.invitation.id).exists())

    def test_permission_denied(self):
        self.force_login(self.GUEST_USER_ID)
        url = f'/m/invitations/'
        resp = self.client.get(url)
        self.assertEqual(resp.status_code, 403)

        resp = self.client.post(url, {'email': 'test@example.com', 'role': 'MEMBER'})
        self.assertEqual(resp.status_code, 403)
