from http import HTTPStatus

from flask import url_for
from flask_jwt_extended import create_access_token

from tests.seeder.factory import UserFactory


def test_get_access_token_for_testing(client, session, jwt_manager, create_user):
    access_token = create_access_token(identity=create_user.id)
    print("\ntest access_token -> ", access_token)
    assert isinstance(access_token, str)


def test_when_user_id_exists_then_check_auth_success(
    client, session, test_request_context, jwt_manager, make_header
):
    user = UserFactory.build()
    session.add(user)
    session.commit()

    access_token = create_access_token(identity=user.id)
    authorization = "Bearer " + access_token
    headers = make_header(authorization=authorization)

    try:
        with test_request_context:
            response = client.get(
                url_for("api/groot.auth_for_testing_view"), headers=headers
            )
    except Exception as e:
        pass

    data = response.get_json()["data"]
    assert response.status_code == 200
    assert data["result"] == "success"


def test_view_when_user_id_not_exists_then_check_auth_failure(
    client, session, test_request_context, jwt_manager, make_header, make_authorization
):
    authorization = make_authorization()
    headers = make_header(authorization=authorization)

    with test_request_context:
        response = client.get(
            url_for("api/groot.auth_for_testing_view"), headers=headers
        )

    assert response.status_code == HTTPStatus.UNAUTHORIZED
    assert response.get_json()["type"] == "unauthorized_error"
