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

import datetime

from freezegun import freeze_time
import pytest

from hotpocket_backend.apps.accounts import tasks as tasks_module
from hotpocket_backend_testing.services.accounts import AuthKeysTestingService
from hotpocket_soa.dto.accounts import AuthKeyOut


@pytest.fixture
def valid_auth_key(auth_key_factory):
    result = auth_key_factory()
    result.created_at = datetime.datetime(
        2019, 12, 6, 8, 0, 0, 0, tzinfo=datetime.timezone.utc,
    )
    result.save()

    return result


@pytest.fixture
def valid_auth_key_out(valid_auth_key):
    return AuthKeyOut.model_validate(valid_auth_key, from_attributes=True)


@pytest.fixture
def expired_auth_key(auth_key_factory):
    result = auth_key_factory()
    result.created_at = datetime.datetime(
        2019, 12, 6, 7, 59, 25, 0, tzinfo=datetime.timezone.utc,
    )
    result.save()

    return result


@pytest.fixture
def expired_auth_key_out(expired_auth_key):
    return AuthKeyOut.model_validate(expired_auth_key, from_attributes=True)


@pytest.fixture
def not_yet_expired_auth_key(auth_key_factory):
    result = auth_key_factory()
    result.created_at = datetime.datetime(
        2019, 12, 6, 7, 59, 30, 0, tzinfo=datetime.timezone.utc,
    )
    result.save()

    return result


@pytest.fixture
def not_yet_expired_auth_key_out(not_yet_expired_auth_key):
    return AuthKeyOut.model_validate(not_yet_expired_auth_key, from_attributes=True)


@freeze_time(
    datetime.datetime(2019, 12, 6, 8, 0, 0, 0, tzinfo=datetime.timezone.utc),
)
@pytest.mark.django_db
def test_ok(valid_auth_key_out,
            not_yet_expired_auth_key_out,
            expired_auth_key_out,
            ):
    # When
    _ = tasks_module.clean_expired_auth_keys()

    # Then
    AuthKeysTestingService().assert_exists(pk=valid_auth_key_out.pk)
    AuthKeysTestingService().assert_exists(pk=not_yet_expired_auth_key_out.pk)
    AuthKeysTestingService().assert_deleted(pk=expired_auth_key_out.pk)
