"""Tests for domain filtering."""

import pytest

from app.domain_filter import DomainFilter


class TestDomainFilter:
    """Tests for the DomainFilter class."""

    def test_exact_domain_match(self):
        """Exact domain should match."""
        df = DomainFilter(["example.com"])
        assert df.is_allowed("https://example.com/path")
        assert df.is_allowed("http://example.com")

    def test_exact_domain_no_match(self):
        """Non-matching domain should be blocked."""
        df = DomainFilter(["example.com"])
        assert not df.is_allowed("https://other.com")
        assert not df.is_allowed("https://sub.example.com")

    def test_wildcard_subdomain_match(self):
        """Wildcard should match subdomains."""
        df = DomainFilter(["*.example.com"])
        assert df.is_allowed("https://sub.example.com")
        assert df.is_allowed("https://deep.sub.example.com")

    def test_wildcard_does_not_match_root(self):
        """Wildcard *.example.com should still match example.com."""
        df = DomainFilter(["*.example.com"])
        # The pattern matches zero or more subdomains
        assert df.is_allowed("https://example.com")

    def test_domain_with_port(self):
        """Domain with port should match."""
        df = DomainFilter(["example.com:8443"])
        assert df.is_allowed("https://example.com:8443/path")
        assert not df.is_allowed("https://example.com/path")

    def test_multiple_domains(self):
        """Multiple domains in allowlist."""
        df = DomainFilter(["example.com", "other.com"])
        assert df.is_allowed("https://example.com")
        assert df.is_allowed("https://other.com")
        assert not df.is_allowed("https://blocked.com")

    def test_case_insensitive(self):
        """Domain matching should be case-insensitive."""
        df = DomainFilter(["Example.Com"])
        assert df.is_allowed("https://example.com")
        assert df.is_allowed("https://EXAMPLE.COM")

    def test_invalid_url_blocked(self):
        """Invalid URLs should be blocked."""
        df = DomainFilter(["example.com"])
        assert not df.is_allowed("not-a-url")
        assert not df.is_allowed("")

    def test_empty_domains_raises(self):
        """Empty allowed_domains should raise ValueError."""
        with pytest.raises(ValueError):
            DomainFilter([])

    def test_get_blocked_reason(self):
        """get_blocked_reason should return informative message."""
        df = DomainFilter(["example.com"])
        reason = df.get_blocked_reason("https://blocked.com/path")
        assert "blocked.com" in reason
        assert "example.com" in reason
