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 TechnicalUserEntity
from src.domain.interfaces import ITechnicalUserRepository
from src.infrastructure.database.models import TechnicalUserModel


def _model_to_entity(m: TechnicalUserModel) -> TechnicalUserEntity:
    return TechnicalUserEntity(
        id=m.id,
        username=m.username,
        email=m.email,
        full_name=m.full_name,
        role=m.role,
        is_active=m.is_active,
        scopes=m.scopes or [],
        last_login_at=m.last_login_at,
        created_at=m.created_at,
        updated_at=m.updated_at,
    )


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

    async def get_by_id(self, user_id: uuid.UUID) -> TechnicalUserEntity | None:
        stmt = select(TechnicalUserModel).where(TechnicalUserModel.id == user_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_username(self, username: str) -> TechnicalUserEntity | None:
        stmt = select(TechnicalUserModel).where(TechnicalUserModel.username == username)
        result = await self._session.execute(stmt)
        model = result.scalar_one_or_none()
        return _model_to_entity(model) if model else None

    async def list_users(self, *, role: str | None = None, is_active: bool | None = None, offset: int = 0, limit: int = 50) -> tuple[Sequence[TechnicalUserEntity], int]:
        filters: list[Any] = []
        if role:
            filters.append(TechnicalUserModel.role == role)
        if is_active is not None:
            filters.append(TechnicalUserModel.is_active == is_active)

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

        stmt = select(TechnicalUserModel).order_by(TechnicalUserModel.username).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: TechnicalUserEntity, password_hash: str) -> TechnicalUserEntity:
        model = TechnicalUserModel(
            username=entity.username,
            email=entity.email,
            full_name=entity.full_name,
            password_hash=password_hash,
            role=entity.role,
            is_active=entity.is_active,
            scopes=entity.scopes,
        )
        self._session.add(model)
        await self._session.flush()
        return _model_to_entity(model)

    async def update(self, entity: TechnicalUserEntity) -> TechnicalUserEntity:
        stmt = update(TechnicalUserModel).where(TechnicalUserModel.id == entity.id).values(
            email=entity.email,
            full_name=entity.full_name,
            role=entity.role,
            is_active=entity.is_active,
            scopes=entity.scopes,
            last_login_at=entity.last_login_at,
        )
        await self._session.execute(stmt)
        await self._session.flush()
        return await self.get_by_id(entity.id)  # type: ignore[return-value]
