"""configs 表：全局键值配置（如 releaseversion）。"""

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.config import Config

RELEASE_VERSION_KEY = "releaseversion"


async def get_config_value(db: AsyncSession, name: str) -> str | None:
    result = await db.execute(select(Config).where(Config.name == name))
    row = result.scalar_one_or_none()
    return row.value if row else None


async def set_config_value(
    db: AsyncSession,
    name: str,
    value: str,
    *,
    mark: str | None = None,
) -> str:
    result = await db.execute(select(Config).where(Config.name == name))
    row = result.scalar_one_or_none()
    if row is None:
        row = Config(name=name, value=value, mark=mark)
        db.add(row)
    else:
        row.value = value
        if mark is not None:
            row.mark = mark
    await db.flush()
    return row.value
