"""Business-rule validators for the Entity domain."""
from __future__ import annotations

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


class EntityNameValidator(BaseValidator):
    """Reject blank or overly-long entity names.

    Usage::

        validator = EntityNameValidator(max_length=120)
        clean_name = await validator.validate("  Acme Corp  ")  # "Acme Corp"
    """

    def __init__(self, max_length: int = 120) -> None:
        self._max = max_length

    async def validate(self, data: str) -> str:
        value = data.strip() if isinstance(data, str) else data
        if not value:
            raise ValidationError("Name cannot be blank.", field="name")
        if len(value) > self._max:
            raise ValidationError(
                f"Name must be at most {self._max} characters.", field="name"
            )
        return value


class EntityIdValidator(BaseValidator):
    """Ensure the entity ID is a non-empty string.

    Usage::

        validator = EntityIdValidator()
        clean_id = await validator.validate("abc-123")
    """

    async def validate(self, data: str) -> str:
        if not data or not str(data).strip():
            raise ValidationError("ID cannot be empty.", field="id")
        return str(data).strip()


def build_entity_pipeline() -> ValidatorPipeline:
    """Return a pipeline that validates ID then name.

    Usage::

        pipeline = build_entity_pipeline()
        clean_name = await pipeline.validate(raw_name)
    """
    return ValidatorPipeline(EntityNameValidator())
