"""Business-rule validators for the Proxy domain."""

from __future__ import annotations

from repo_core.base.validators import BaseValidator, ValidationError, ValidatorPipeline


class ProxyAddressValidator(BaseValidator):
    """Reject blank proxy addresses.

    Usage::

        validator = ProxyAddressValidator()
        clean_addr = await validator.validate("212.212.18.77")
    """

    async def validate(self, data: str) -> str:
        value = data.strip() if isinstance(data, str) else data
        if not value:
            raise ValidationError("Proxy address cannot be blank.", field="proxy_address")
        return value


class ProxyPortValidator(BaseValidator):
    """Reject invalid port numbers.

    Usage::

        validator = ProxyPortValidator()
        clean_port = await validator.validate(6728)
    """

    async def validate(self, data: int) -> int:
        if not isinstance(data, int) or data < 1 or data > 65535:
            raise ValidationError(
                f"Port must be between 1 and 65535, got {data}.", field="port"
            )
        return data


def build_proxy_pipeline() -> ValidatorPipeline:
    """Return a ready-to-use pipeline that validates proxy address then port.

    Usage::

        pipeline = build_proxy_pipeline()
        result = await pipeline.run({"proxy_address": "...", "port": 8080})
    """
    return ValidatorPipeline([ProxyAddressValidator(), ProxyPortValidator()])
