import pytest
import httpx

from src.core.exceptions import ValidationError
from src.domain.domains.service import normalize_domain
from src.domain.domains.router import _registrar_http_error
from src.domain.domains.providers import CloudflareRegistrarProvider


def test_normalize_domain_accepts_url_and_trailing_dot():
    assert normalize_domain("https://WWW.Example.com./") == "www.example.com"


@pytest.mark.parametrize("value", ["example", "example..com", "-example.com", "example.com/path"])
def test_normalize_domain_rejects_invalid_hosts(value):
    with pytest.raises(ValidationError):
        normalize_domain(value)


def test_registrar_auth_failure_is_actionable():
    request = httpx.Request("GET", "https://api.cloudflare.com/client/v4/accounts/test/registrar/domain-search")
    response = httpx.Response(403, request=request)
    error = httpx.HTTPStatusError("forbidden", request=request, response=response)
    assert "account authorization" in _registrar_http_error(error)


def test_registrar_provider_prefers_dedicated_credentials(monkeypatch):
    class Settings:
        cloudflare_registrar_account_id = "registrar-account"
        cloudflare_registrar_api_token = "registrar-token"
        cloudflare_account_id = "hosting-account"
        cloudflare_api_token = "hosting-token"

    monkeypatch.setattr("src.domain.domains.providers.get_settings", lambda: Settings())
    provider = CloudflareRegistrarProvider()
    assert provider._account_id() == "registrar-account"
    assert provider._api_token() == "registrar-token"
