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

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

from server.domain.models import DbCredential


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

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

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

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

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

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