"""Тесты провайдера WHOIS на python-whois 0.9.6."""

from __future__ import annotations

import asyncio
from datetime import datetime, timezone

import pytest

from ioc_checker.config import settings
from ioc_checker.iocs.domain import DOMAINIndicator
from ioc_checker.providers.whois import ProxyWhoisClient, WhoisProvider
from whois.exceptions import PywhoisError


def test_whois_fetch_serializes_response(monkeypatch: pytest.MonkeyPatch) -> None:
    called_with: list[tuple[str, int, str]] = []

    def _fake_lookup(self: ProxyWhoisClient, domain: str) -> dict[str, object]:
        called_with.append((self.proxy_host, self.proxy_port, domain))
        return {
            "domain_name": domain,
            "creation_date": datetime(2023, 1, 1, tzinfo=timezone.utc),
            "expiration_date": datetime(2024, 1, 1, tzinfo=timezone.utc),
            "nameservers": {"ns1.example.com", "ns2.example.com"},
        }

    monkeypatch.setattr(settings, "http_proxy", "http://127.0.0.1:8080")
    monkeypatch.setattr(ProxyWhoisClient, "lookup", _fake_lookup)

    provider = WhoisProvider()
    indicator = DOMAINIndicator(value="example.com", kinds=frozenset())

    async def _run() -> dict[str, object] | bool:
        async with provider.get_context() as context:
            return await provider.fetch(indicator, context)

    payload = asyncio.run(_run())

    assert payload["domain_name"] == "example.com"
    assert payload["creation_date"] == "2023-01-01T00:00:00+00:00"
    assert payload["expiration_date"] == "2024-01-01T00:00:00+00:00"
    assert sorted(payload["nameservers"]) == ["ns1.example.com", "ns2.example.com"]

    assert called_with == [("127.0.0.1", 8080, "example.com")]


def test_whois_fetch_returns_empty_on_pywhois_error(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def _failing_whois(self: ProxyWhoisClient, domain: str) -> dict[str, object]:
        raise PywhoisError(f"Нет данных для {domain}")

    monkeypatch.setattr(settings, "http_proxy", "http://127.0.0.1:8080")
    monkeypatch.setattr(ProxyWhoisClient, "lookup", _failing_whois)

    provider = WhoisProvider()
    indicator = DOMAINIndicator(value="absent.example", kinds=frozenset())

    async def _run() -> dict[str, object] | bool:
        async with provider.get_context() as context:
            return await provider.fetch(indicator, context)

    payload = asyncio.run(_run())

    assert payload == {}


def test_whois_build_features_matches_domain() -> None:
    provider = WhoisProvider()
    indicator = DOMAINIndicator(value="example.com", kinds=frozenset())

    payload = {
        "domain_name": ["example.com", "other.com"],
        "registrar": ["Test Registrar LLC"],
        "creation_date": "2022-01-01",
        "expiration_date": "2024-01-01",
    }

    features = provider.build_features(payload, indicator=indicator)

    assert features["whois_exists"] is True
    assert features["whois_domain_match"] is True
    assert features["whois_registrar"] == "test"
    assert features["whois_reg_period_days"] == 730
