"""SQLAlchemy Type for TypeIDs."""

from typing import TYPE_CHECKING

from sqlalchemy.types import VARCHAR, TypeDecorator

from .typeid import TypeID

if TYPE_CHECKING:
    from sqlalchemy import Dialect


class TypeIdSaType(TypeDecorator[TypeID]):
    """SQLAlchemy Type for TypeID."""

    impl = VARCHAR(90)

    cache_ok = True

    def process_bind_param(
        self,
        value: TypeID | None,
        dialect: "Dialect",  # noqa: ARG002
    ) -> str | None:
        """Convert TypeID into string to be stored in the database."""
        if value is not None:
            return str(value)
        return None

    def process_result_value(
        self,
        value: str | None,
        dialect: "Dialect",  # noqa: ARG002
    ) -> TypeID | None:
        """Convert string from database into TypeID."""
        if value:
            return TypeID.from_string(value)
        return None
