"""Nexus — Setting Repository (Async SQLAlchemy)"""

from typing import Optional, List
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.mysql import insert as mysql_insert

from server.domain.models import Setting


class SettingRepositoryImpl:
    def __init__(self, session: AsyncSession):
        self.session = session

    async def get(self, key: str) -> Optional[str]:
        result = await self.session.execute(select(Setting).where(Setting.key == key))
        setting = result.scalar_one_or_none()
        return setting.value if setting else None

    async def set(self, key: str, value: str) -> Setting:
        """Upsert a setting — uses MySQL ON DUPLICATE KEY UPDATE to avoid SELECT-then-INSERT race"""
        stmt = mysql_insert(Setting).values(key=key, value=value)
        stmt = stmt.on_duplicate_key_update(value=value)
        await self.session.execute(stmt)
        await self.session.commit()
        result = await self.session.execute(select(Setting).where(Setting.key == key))
        return result.scalar_one()

    async def get_all(self) -> List[Setting]:
        result = await self.session.execute(select(Setting).order_by(Setting.key))
        return list(result.scalars().all())