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

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

from server.domain.models import SshKeyPreset


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

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

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

    async def create(self, preset: SshKeyPreset) -> SshKeyPreset:
        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: SshKeyPreset) -> SshKeyPreset:
        await self.session.commit()
        await self.session.refresh(preset)
        return preset
