# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations

import http

from django.test import Client
from django.urls import reverse
import pytest
from pytest_django import asserts

from hotpocket_backend_testing.services.accounts import AuthKeysTestingService
from hotpocket_common.url import URL


@pytest.mark.django_db
def test_ok(authenticated_client: Client,
            extension_auth_source_extension,
            account,
            ):
    # When
    result = authenticated_client.get(
        reverse('ui.integrations.extension.authenticate'),
        follow=False,
    )

    # Then
    assert result.status_code == http.HTTPStatus.FOUND
    assert 'Location' in result.headers

    redirect_url = URL(result.headers['Location'])
    assert redirect_url.raw_path == reverse('ui.integrations.extension.post_authenticate')
    assert 'auth_key' in redirect_url.query

    assert 'extension_source' in authenticated_client.session
    assert authenticated_client.session['extension_source'] == extension_auth_source_extension

    assert 'extension_session_token' in authenticated_client.session

    AuthKeysTestingService().assert_created(
        key=redirect_url.query['auth_key'][0],
        account_uuid=account.pk,
    )


@pytest.mark.parametrize(
    'source_fixture_name',
    ['extension_auth_source_desktop', 'extension_auth_source_mobile'],
)
@pytest.mark.django_db
def test_ok_with_source(source_fixture_name,
                        request: pytest.FixtureRequest,
                        authenticated_client: Client,
                        extension_auth_session_token,
                        ):
    # Given
    source = request.getfixturevalue(source_fixture_name)

    # When
    result = authenticated_client.get(
        reverse(
            'ui.integrations.extension.authenticate',
            query=[
                ('source', source),
                ('session_token', extension_auth_session_token),
            ],
        ),
        follow=False,
    )

    # Then
    assert result.status_code == http.HTTPStatus.FOUND
    assert 'Location' in result.headers

    redirect_url = URL(result.headers['Location'])
    assert redirect_url.raw_path == reverse('ui.integrations.extension.post_authenticate')
    assert 'auth_key' in redirect_url.query

    assert 'extension_source' in authenticated_client.session
    assert authenticated_client.session['extension_source'] == source

    assert 'extension_session_token' in authenticated_client.session
    assert authenticated_client.session['extension_session_token'] == extension_auth_session_token


@pytest.mark.django_db
def test_source_without_session_token(authenticated_client: Client,
                                      extension_auth_source_desktop,
                                      ):
    # Given
    with pytest.raises(AssertionError) as exception_info:
        # When
        _ = authenticated_client.get(
            reverse(
                'ui.integrations.extension.authenticate',
                query=[
                    ('source', extension_auth_source_desktop),
                ],
            ),
            follow=False,
        )

    # Then
    assert exception_info.value.args[0] == 'Session token missing'


@pytest.mark.django_db
def test_source_without_empty_session_token(authenticated_client: Client,
                                            extension_auth_source_desktop,
                                            ):
    # Given
    with pytest.raises(AssertionError) as exception_info:
        # When
        _ = authenticated_client.get(
            reverse(
                'ui.integrations.extension.authenticate',
                query=[
                    ('source', extension_auth_source_desktop),
                    ('session_token', ''),
                ],
            ),
            follow=False,
        )

    # Then
    assert exception_info.value.args[0] == 'Session token missing'


@pytest.mark.django_db
def test_unknown_source(authenticated_client: Client, extension_auth_session_token):
    # Given
    with pytest.raises(ValueError) as exception_info:
        # When
        _ = authenticated_client.get(
            reverse(
                'ui.integrations.extension.authenticate',
                query=[
                    ('source', 'thisisntright'),
                    ('session_token', extension_auth_session_token),
                ],
            ),
            follow=False,
        )

    # Then
    assert exception_info.value.args[0] == 'Unknown source: `thisisntright`'


@pytest.mark.django_db
def test_inactive_account(inactive_account_client: Client):
    # When
    result = inactive_account_client.get(
        reverse('ui.integrations.extension.authenticate'),
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse(
            'ui.accounts.login',
            query=[('next', reverse('ui.integrations.extension.authenticate'))],
        ),
        fetch_redirect_response=False,
    )


@pytest.mark.django_db
def test_anonymous(client: Client):
    # When
    result = client.get(
        reverse('ui.integrations.extension.authenticate'),
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse(
            'ui.accounts.login',
            query=[('next', reverse('ui.integrations.extension.authenticate'))],
        ),
        fetch_redirect_response=False,
    )
