"""数据库配置"""
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.pool import NullPool

from app.core.config import get_settings

settings = get_settings()

# 创建异步引擎
if settings.DEBUG:
    # 开发环境使用 NullPool，不需要连接池参数
    engine = create_async_engine(
        settings.DATABASE_URL, 
        echo=False, 
        pool_pre_ping=True, 
        poolclass=NullPool,
        # 确保 MySQL 连接使用 UTF-8 字符集
        connect_args={
            "charset": "utf8mb4",
            "use_unicode": True,
            "autocommit": False,
            "init_command": "SET character_set_client=utf8mb4, character_set_connection=utf8mb4, character_set_results=utf8mb4, collation_connection=utf8mb4_unicode_ci",
        } if "mysql" in settings.DATABASE_URL else {},
    )
else:
    # 生产环境使用连接池
    engine = create_async_engine(
        settings.DATABASE_URL,
        echo=False,
        pool_size=20,
        max_overflow=0,
        pool_pre_ping=True,
        # 确保 MySQL 连接使用 UTF-8 字符集
        connect_args={
            "charset": "utf8mb4",
            "use_unicode": True,
            "autocommit": False,
            "init_command": "SET character_set_client=utf8mb4, character_set_connection=utf8mb4, character_set_results=utf8mb4, collation_connection=utf8mb4_unicode_ci",
        } if "mysql" in settings.DATABASE_URL else {},
    )

# 创建异步会话工厂
SessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)
