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

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

from src.domain.entities import ReservationEntity
from src.domain.interfaces import IReservationRepository
from src.infrastructure.database.models import ReservationModel


def _model_to_entity(m: ReservationModel) -> ReservationEntity:
    return ReservationEntity(
        id=m.id,
        pharmacy_id=m.pharmacy_id,
        medication_id=m.medication_id,
        user_id=m.user_id,
        external_reference=m.external_reference,
        quantity=m.quantity,
        status=m.status,
        expires_at=m.expires_at,
        confirmed_at=m.confirmed_at,
        cancelled_at=m.cancelled_at,
        idempotency_key=m.idempotency_key,
        metadata_=m.metadata_,
        created_at=m.created_at,
        updated_at=m.updated_at,
    )


def _entity_to_model_data(e: ReservationEntity) -> dict[str, Any]:
    return {
        "pharmacy_id": e.pharmacy_id,
        "medication_id": e.medication_id,
        "user_id": e.user_id,
        "external_reference": e.external_reference,
        "quantity": e.quantity,
        "status": e.status,
        "expires_at": e.expires_at,
        "confirmed_at": e.confirmed_at,
        "cancelled_at": e.cancelled_at,
        "idempotency_key": e.idempotency_key,
        "metadata_": e.metadata_,
    }


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

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

    async def get_by_idempotency_key(self, key: str) -> ReservationEntity | None:
        stmt = select(ReservationModel).where(ReservationModel.idempotency_key == key)
        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[ReservationEntity], int]:
        filters: list[Any] = [ReservationModel.pharmacy_id == pharmacy_id]
        if status:
            filters.append(ReservationModel.status == status)

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

        stmt = (
            select(ReservationModel)
            .where(*filters)
            .order_by(ReservationModel.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: ReservationEntity) -> ReservationEntity:
        model = ReservationModel(**_entity_to_model_data(entity))
        self._session.add(model)
        await self._session.flush()
        return _model_to_entity(model)

    async def update(self, entity: ReservationEntity) -> ReservationEntity:
        data = _entity_to_model_data(entity)
        stmt = update(ReservationModel).where(ReservationModel.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]
