"""System repository — all DB queries for system-wide configuration (SystemConfig)."""

from datetime import datetime, timezone

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

from app.models.system import SystemConfig

MAINTENANCE_KEY = "maintenance_mode"
ENV_MODE_KEY = "environment_mode"
NUMBER_THOUSAND_SEP_KEY = "number_thousand_separator"
NUMBER_DECIMAL_SEP_KEY = "number_decimal_separator"
NUMBER_DECIMAL_PLACES_KEY = "number_decimal_places"
NUMBER_NEGATIVE_FORMAT_KEY = "number_negative_format"
NUMBER_NEGATIVE_COLOR_KEY = "number_negative_color"


async def get_config(db: AsyncSession, key: str) -> SystemConfig | None:
    """Fetch a system config entry by key, or None if it does not exist."""
    result = await db.execute(select(SystemConfig).where(SystemConfig.key == key))
    return result.scalar_one_or_none()


async def set_config(
    db: AsyncSession, key: str, value: str, user_id: int | None = None
) -> SystemConfig:
    """Upsert a system config entry (insert if new, update if existing)."""
    config = await get_config(db, key)
    if config is None:
        config = SystemConfig(
            key=key,
            value=value,
            updated_by_id=user_id,
            updated_at=datetime.now(timezone.utc),
        )
        db.add(config)
    else:
        config.value = value
        config.updated_by_id = user_id
        config.updated_at = datetime.now(timezone.utc)
    await db.flush()
    await db.refresh(config)
    return config


async def is_maintenance_mode(db: AsyncSession) -> bool:
    """Return True if the system is currently in maintenance mode."""
    config = await get_config(db, MAINTENANCE_KEY)
    return config is not None and config.value == "true"


async def is_dev_mode(db: AsyncSession) -> bool:
    """Return True if environment_mode is 'development'."""
    config = await get_config(db, ENV_MODE_KEY)
    return config is not None and config.value == "development"
