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 ERPSystemEntity
from src.domain.interfaces import IERPSystemRepository
from src.infrastructure.database.models import ERPSystemModel


def _model_to_entity(m: ERPSystemModel) -> ERPSystemEntity:
    return ERPSystemEntity(
        id=m.id,
        name=m.name,
        erp_type=m.erp_type,
        version=m.version,
        base_url=m.base_url,
        auth_config=m.auth_config,
        status=m.status,
        metadata_=m.metadata_,
        created_at=m.created_at,
        updated_at=m.updated_at,
    )


def _entity_to_model_data(e: ERPSystemEntity) -> dict[str, Any]:
    return {
        "name": e.name,
        "erp_type": e.erp_type if isinstance(e.erp_type, str) else e.erp_type.value,
        "version": e.version,
        "base_url": e.base_url,
        "auth_config": e.auth_config,
        "status": e.status if isinstance(e.status, str) else e.status.value,
        "metadata_": e.metadata_,
    }


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

    async def get_by_id(self, erp_id: uuid.UUID) -> ERPSystemEntity | None:
        stmt = select(ERPSystemModel).where(ERPSystemModel.id == erp_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_erp_systems(
        self,
        *,
        erp_type: str | None = None,
        offset: int = 0,
        limit: int = 50,
    ) -> tuple[Sequence[ERPSystemEntity], int]:
        filters: list[Any] = []
        if erp_type:
            filters.append(ERPSystemModel.erp_type == erp_type)

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

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

    async def update(self, entity: ERPSystemEntity) -> ERPSystemEntity:
        data = _entity_to_model_data(entity)
        stmt = update(ERPSystemModel).where(ERPSystemModel.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, erp_id: uuid.UUID) -> bool:
        stmt = delete(ERPSystemModel).where(ERPSystemModel.id == erp_id)
        result = await self._session.execute(stmt)
        return result.rowcount > 0
