from account.views import LoginRockyView
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import Client
from pytest_django.asserts import assertContains


def test_login_view(rf, clientuser):
    request = rf.get("login")

    request = SessionMiddleware(lambda r: r)(request)
    request = AuthenticationMiddleware(lambda r: r)(request)

    response = LoginRockyView.as_view()(request)
    assert response.status_code == 200
    assertContains(response, "Login")
    assertContains(response, "Email")
    assertContains(response, "Password")
    assertContains(response, "csrfmiddlewaretoken")


def test_login(superuser):
    client = Client()

    response = client.post(
        "/en/login/",
        {
            "auth-username": "wrong@openkat.nl",
            "auth-password": "TestTest123!!",
            "login_rocky_view-current_step": "auth",
        },
    )

    assert response.status_code == 200
    assertContains(response, "Error")
    assertContains(response, "Please enter a correct email address and password.")

    response = client.post(
        "/en/login/",
        {"auth-username": "admin@openkat.nl", "auth-password": "Test!!", "login_rocky_view-current_step": "auth"},
    )

    assert response.status_code == 200
    assertContains(response, "Login")
    assertContains(response, "Error")
    assertContains(response, "Please enter a correct email address and password.")

    response = client.post(
        "/en/login/",
        {"auth-username": superuser.email, "auth-password": "SuperSuper123!!", "login_rocky_view-current_step": "auth"},
    )

    assert response.status_code == 200

    assertContains(response, "Explanation:")
    assertContains(response, "Insert the token generated by your token authenticator app.")
    assertContains(response, "Submit")

    response = client.post("/en/login/", {"token-otp_token": "123456", "login_rocky_view-current_step": "token"})

    assert response.status_code == 200

    assert not client.login(email="wrong@openkat.nl", password="TestTest123!!")
    assert not client.login(email="admin@openkat.nl", password="Test!!")
    assert client.login(email=superuser.email, password="SuperSuper123!!")
