from enum import Enum
from typing import Union

from galtea.utils.case_insensitive_enum import CaseInsensitiveEnumMixin


class SortOrder(CaseInsensitiveEnumMixin, str, Enum):
    ASC = "asc"
    DESC = "desc"


def normalize_sort_order(value: Union[str, SortOrder]) -> str:
    """Normalize a sort order value to its lowercase string representation.

    Args:
        value: The sort order as a string (case-insensitive) or SortOrder enum.

    Returns:
        The normalized sort order string ("asc" or "desc").

    Raises:
        ValueError: If the value is not a valid sort order.
    """
    if isinstance(value, SortOrder):
        return value.value

    if isinstance(value, str):
        normalized = value.strip().lower()
        if normalized in ("asc", "desc"):
            return normalized

    raise ValueError(f"Invalid sort order: '{value}'. Must be 'asc' or 'desc'.")
