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

from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.entities import SyncJobEntity, SyncJobStatus
from src.domain.interfaces import ISyncJobRepository
from src.infrastructure.database.models import SyncJobModel


def _model_to_entity(m: SyncJobModel) -> SyncJobEntity:
    return SyncJobEntity(
        id=m.id,
        pharmacy_id=m.pharmacy_id,
        connector_id=m.connector_id,
        strategy=m.strategy,
        status=m.status,
        started_at=m.started_at,
        completed_at=m.completed_at,
        items_total=m.items_total,
        items_processed=m.items_processed,
        items_failed=m.items_failed,
        error_message=m.error_message,
        metadata_=m.metadata_,
        created_at=m.created_at,
        updated_at=m.updated_at,
    )


def _entity_to_model_data(e: SyncJobEntity) -> dict[str, Any]:
    return {
        "pharmacy_id": e.pharmacy_id,
        "connector_id": e.connector_id,
        "strategy": e.strategy,
        "status": e.status,
        "started_at": e.started_at,
        "completed_at": e.completed_at,
        "items_total": e.items_total,
        "items_processed": e.items_processed,
        "items_failed": e.items_failed,
        "error_message": e.error_message,
        "metadata_": e.metadata_,
    }


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

    async def get_by_id(self, job_id: uuid.UUID) -> SyncJobEntity | None:
        stmt = select(SyncJobModel).where(SyncJobModel.id == job_id)
        result = await self._session.execute(stmt)
        model = result.scalar_one_or_none()
        return _model_to_entity(model) if model else None

    async def list_by_pharmacy(
        self,
        pharmacy_id: uuid.UUID,
        *,
        status: str | None = None,
        offset: int = 0,
        limit: int = 50,
    ) -> tuple[Sequence[SyncJobEntity], int]:
        filters: list[Any] = [SyncJobModel.pharmacy_id == pharmacy_id]
        if status:
            filters.append(SyncJobModel.status == status)

        count_stmt = select(func.count()).select_from(SyncJobModel).where(*filters)
        total = (await self._session.execute(count_stmt)).scalar() or 0

        stmt = (
            select(SyncJobModel)
            .where(*filters)
            .order_by(SyncJobModel.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], total

    async def create(self, entity: SyncJobEntity) -> SyncJobEntity:
        model = SyncJobModel(**_entity_to_model_data(entity))
        self._session.add(model)
        await self._session.flush()
        return _model_to_entity(model)

    async def update(self, entity: SyncJobEntity) -> SyncJobEntity:
        data = _entity_to_model_data(entity)
        stmt = update(SyncJobModel).where(SyncJobModel.id == entity.id).values(**data)
        await self._session.execute(stmt)
        await self._session.flush()
        return await self.get_by_id(entity.id)  # type: ignore[return-value]
