"""PostgreSQL connection pool."""

from __future__ import annotations

import logging

from psycopg_pool import AsyncConnectionPool

from config import DATABASE_URL

logger = logging.getLogger("mail_summary")

_pool: AsyncConnectionPool | None = None
_pool_enabled = False


async def init_pool() -> None:
    global _pool, _pool_enabled
    if _pool is not None:
        return

    try:
        pool = AsyncConnectionPool(
            conninfo=DATABASE_URL,
            min_size=1,
            max_size=10,
            open=False,
        )
        await pool.open()
        _pool = pool
        _pool_enabled = True
        logger.info("PostgreSQL connection pool initialized")
    except Exception:
        _pool = None
        _pool_enabled = False
        logger.exception("PostgreSQL unavailable")


async def close_pool() -> None:
    global _pool, _pool_enabled
    if _pool is None:
        return
    await _pool.close()
    _pool = None
    _pool_enabled = False
    logger.info("PostgreSQL connection pool closed")


def pool_enabled() -> bool:
    return _pool_enabled and _pool is not None


def get_pool() -> AsyncConnectionPool:
    if _pool is None:
        raise RuntimeError("Database pool is not initialized")
    return _pool
