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

import http
from unittest import mock

from celery.result import AsyncResult
from django.test import Client
from django.urls import reverse
import pytest
from pytest_django import asserts
import pytest_mock

from hotpocket_backend_testing.services.saves import SaveProcessorTestingService


@pytest.fixture
def async_result(null_uuid) -> mock.Mock:
    result = mock.Mock(spec=AsyncResult)
    result.id = str(null_uuid)

    return result


@pytest.fixture
def mock_saves_process_save_task_apply_async(mocker: pytest_mock.MockerFixture,
                                             async_result,
                                             ) -> mock.Mock:
    return SaveProcessorTestingService().mock_process_save_task_apply_async(
        mocker=mocker, async_result=async_result,
    )


@pytest.mark.django_db
def test_ok(authenticated_client: Client,
            association_out,
            mock_saves_process_save_task_apply_async: mock.Mock,
            save_out,
            ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(association_out.pk,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse('ui.associations.browse'),
        fetch_redirect_response=False,
    )

    mock_saves_process_save_task_apply_async.assert_called_once_with(
        kwargs={
            'pk': save_out.pk,
        },
    )


@pytest.mark.django_db
def test_ok_htmx(mock_saves_process_save_task_apply_async: mock.Mock,
                 authenticated_client: Client,
                 association_out,
                 async_result,
                 ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(association_out.pk,)),
        headers={
            'HX-Request': 'true',
        },
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.OK

    expected_payload = {
        'status': 'ok',
        'result': async_result.id,
    }
    assert result.json() == expected_payload


@pytest.mark.django_db
def test_invalid_all_missing(authenticated_client: Client,
                             association_out,
                             mock_saves_process_save_task_apply_async: mock.Mock,
                             ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(association_out.pk,)),
        data={
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.OK

    mock_saves_process_save_task_apply_async.assert_not_called()

    assert 'canhazconfirm' in result.context['form'].errors


@pytest.mark.django_db
def test_invalid_all_empty(authenticated_client: Client,
                           association_out,
                           mock_saves_process_save_task_apply_async: mock.Mock,
                           ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(association_out.pk,)),
        data={
            'canhazconfirm': '',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.OK

    mock_saves_process_save_task_apply_async.assert_not_called()

    assert 'canhazconfirm' in result.context['form'].errors


@pytest.mark.django_db
def test_archived(authenticated_client: Client,
                  archived_association_out,
                  ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(archived_association_out.pk,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.NOT_FOUND


@pytest.mark.django_db
def test_deleted(authenticated_client: Client,
                 deleted_association_out,
                 ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(deleted_association_out.pk,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.NOT_FOUND


@pytest.mark.django_db
def test_not_found(authenticated_client: Client,
                   null_uuid,
                   ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(null_uuid,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.NOT_FOUND


@pytest.mark.django_db
def test_other_account_association(authenticated_client: Client,
                                   other_account_association_out,
                                   ):
    # When
    result = authenticated_client.post(
        reverse('ui.associations.refresh', args=(other_account_association_out.pk,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.FORBIDDEN


@pytest.mark.django_db
def test_inactive_account(inactive_account_client: Client,
                          association_out,
                          ):
    # When
    result = inactive_account_client.post(
        reverse('ui.associations.refresh', args=(association_out.pk,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse(
            'ui.accounts.login',
            query=[
                ('next', reverse('ui.associations.refresh', args=(association_out.pk,))),
            ],
        ),
        fetch_redirect_response=False,
    )


@pytest.mark.django_db
def test_anonymous(client: Client,
                   association_out,
                   ):
    # When
    result = client.post(
        reverse('ui.associations.refresh', args=(association_out.pk,)),
        data={
            'canhazconfirm': 'hai',
        },
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse(
            'ui.accounts.login',
            query=[
                ('next', reverse('ui.associations.refresh', args=(association_out.pk,))),
            ],
        ),
        fetch_redirect_response=False,
    )
