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

from typing import Optional, List
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from server.domain.models import PasswordPreset


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

    async def get_by_id(self, id: int) -> Optional[PasswordPreset]:
        result = await self.session.execute(select(PasswordPreset).where(PasswordPreset.id == id))
        return result.scalar_one_or_none()

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

    async def create(self, preset: PasswordPreset) -> PasswordPreset:
        self.session.add(preset)
        await self.session.commit()
        return preset

    async def delete(self, id: int) -> bool:
        preset = await self.get_by_id(id)
        if preset:
            await self.session.delete(preset)
            await self.session.commit()
            return True
        return False

    async def update(self, preset: PasswordPreset) -> PasswordPreset:
        await self.session.commit()
        await self.session.refresh(preset)
        return preset