import uuid
from collections.abc import Sequence
from typing import Any

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.entities import SyncLogEntity
from src.domain.interfaces import ISyncLogRepository
from src.infrastructure.database.models import SyncLogModel


def _model_to_entity(m: SyncLogModel) -> SyncLogEntity:
    return SyncLogEntity(
        id=m.id,
        sync_job_id=m.sync_job_id,
        level=m.level,
        message=m.message,
        details=m.details,
        created_at=m.created_at,
    )


class SyncLogRepository(ISyncLogRepository):
    def __init__(self, session: AsyncSession) -> None:
        self._session = session

    async def add(self, entity: SyncLogEntity) -> SyncLogEntity:
        model = SyncLogModel(
            sync_job_id=entity.sync_job_id,
            level=entity.level,
            message=entity.message,
            details=entity.details,
        )
        self._session.add(model)
        await self._session.flush()
        return _model_to_entity(model)

    async def list_by_job(
        self,
        job_id: uuid.UUID,
        *,
        level: str | None = None,
        offset: int = 0,
        limit: int = 100,
    ) -> Sequence[SyncLogEntity]:
        stmt = select(SyncLogModel).where(SyncLogModel.sync_job_id == job_id)
        if level:
            stmt = stmt.where(SyncLogModel.level == level)
        stmt = stmt.order_by(SyncLogModel.created_at.desc()).offset(offset).limit(limit)
        result = await self._session.execute(stmt)
        models = result.scalars().all()
        return [_model_to_entity(m) for m in models]
