import uuid
from django.http import HttpRequest
from django.test import TestCase

from apps.lyric.authentication import PasswordlessAuthenticationBackend
from apps.lyric.models import LoginToken, User


class AuthenticateTest(TestCase):
    def test_returns_None_if_login_token_uuid_not_found(self):
        uid = uuid.uuid4()
        result = PasswordlessAuthenticationBackend().authenticate(
            HttpRequest(), uid
        )
        self.assertIsNone(result)

    def test_returns_new_user_with_correct_email_if_login_token_exists(self):
        email = "discoman@example.com"
        login_token = LoginToken.objects.create(email=email)
        user = PasswordlessAuthenticationBackend().authenticate(
            HttpRequest(), login_token.uid
        )
        new_user = User.objects.get(email=email)
        self.assertEqual(user, new_user)

    def test_returns_existing_user_with_correct_email_if_login_token_exists(self):
        email = "discoman@example.com"
        existing_user = User.objects.create(email=email)
        login_token = LoginToken.objects.create(email=email)
        user = PasswordlessAuthenticationBackend().authenticate(
            HttpRequest(), login_token.uid
        )
        self.assertEqual(user, existing_user)

    def test_can_retrieve_login_token_by_uuid(self):
        login_token = LoginToken.objects.create(email="a@b.cde")
        fetched = LoginToken.objects.get(pk=login_token.uid)
        self.assertEqual(fetched, login_token)

class GetUserTest(TestCase):
    def test_gets_user_by_uuid(self):
        User.objects.create(email="fantaman@example.com")
        desired_user = User.objects.create(email="discoman@example.com")
        found_user = PasswordlessAuthenticationBackend().get_user(desired_user.id)
        self.assertEqual(found_user, desired_user)

    def test_returns_None_if_no_user_with_that_email(self):
        self.assertIsNone(
            PasswordlessAuthenticationBackend().get_user(999)
        )
