"""Async SQLAlchemy engine singleton."""
from __future__ import annotations

import functools

from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine


@functools.lru_cache(maxsize=1)
def get_engine(dsn: str | None = None) -> AsyncEngine:
    from libs.common.config import get_settings

    target_dsn = dsn or get_settings().postgres_dsn
    return create_async_engine(
        target_dsn,
        echo=False,
        pool_pre_ping=True,
        pool_size=5,
        max_overflow=10,
    )
