# src/infrastructure/adapters/sqlserver/sql_token_repository.py
from sqlalchemy import select, delete
from sqlalchemy.ext.asyncio import AsyncSession
from src.domain.ports.repositories.token_repository import TokenRepositoryPort
from src.infrastructure.persistence.models import BlacklistedTokenModel
from datetime import datetime

class SqlTokenRepository(TokenRepositoryPort):
    def __init__(self, session: AsyncSession):
        self._session = session

    async def add_to_blacklist(self, token: str, expires_at: datetime) -> None:
        blacklisted_token = BlacklistedToken(
            token=token,
            expires_at=expires_at
        )
        self._session.add(blacklisted_token)
        await self._session.commit()

    async def is_blacklisted(self, token: str) -> bool:
        result = await self._session.execute(
            select(BlacklistedToken).where(BlacklistedToken.token == token)
        )
        return result.scalar_one_or_none() is not None

    async def cleanup_expired(self) -> None:
        """Remove expired tokens from blacklist"""
        await self._session.execute(
            delete(BlacklistedToken).where(BlacklistedToken.expires_at < datetime.now())
        )
        await self._session.commit()