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 ConnectorEntity, ConnectorStatus
from src.domain.interfaces import IConnectorRepository
from src.infrastructure.database.models import ConnectorModel


def _model_to_entity(m: ConnectorModel) -> ConnectorEntity:
    return ConnectorEntity(
        id=m.id,
        erp_system_id=m.erp_system_id,
        pharmacy_id=m.pharmacy_id,
        name=m.name,
        connector_type=m.connector_type,
        version=m.version,
        config=m.config,
        status=m.status,
        last_heartbeat_at=m.last_heartbeat_at,
        last_error=m.last_error,
        metadata_=m.metadata_,
        created_at=m.created_at,
        updated_at=m.updated_at,
    )


def _entity_to_model_data(e: ConnectorEntity) -> dict[str, Any]:
    return {
        "erp_system_id": e.erp_system_id,
        "pharmacy_id": e.pharmacy_id,
        "name": e.name,
        "connector_type": e.connector_type if isinstance(e.connector_type, str) else e.connector_type.value,
        "version": e.version,
        "config": e.config,
        "status": e.status if isinstance(e.status, str) else e.status.value,
        "last_heartbeat_at": e.last_heartbeat_at,
        "last_error": e.last_error,
        "metadata_": e.metadata_,
    }


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

    async def get_by_id(self, connector_id: uuid.UUID) -> ConnectorEntity | None:
        stmt = select(ConnectorModel).where(ConnectorModel.id == connector_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_connectors(
        self,
        *,
        erp_system_id: uuid.UUID | None = None,
        pharmacy_id: uuid.UUID | None = None,
        status: str | None = None,
        offset: int = 0,
        limit: int = 50,
    ) -> tuple[Sequence[ConnectorEntity], int]:
        filters: list[Any] = []
        if erp_system_id:
            filters.append(ConnectorModel.erp_system_id == erp_system_id)
        if pharmacy_id:
            filters.append(ConnectorModel.pharmacy_id == pharmacy_id)
        if status:
            filters.append(ConnectorModel.status == status)

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

        stmt = select(ConnectorModel).order_by(ConnectorModel.name).offset(offset).limit(limit)
        if filters:
            stmt = stmt.where(*filters)
        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: ConnectorEntity) -> ConnectorEntity:
        model = ConnectorModel(**_entity_to_model_data(entity))
        self._session.add(model)
        await self._session.flush()
        return _model_to_entity(model)

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

    async def delete(self, connector_id: uuid.UUID) -> bool:
        stmt = delete(ConnectorModel).where(ConnectorModel.id == connector_id)
        result = await self._session.execute(stmt)
        return result.rowcount > 0
