from __future__ import annotations

import asyncio
from typing import Any, Dict, List

from appwrite.exception import AppwriteException
from appwrite.query import Query
from appwrite.services.databases import Databases
from fastapi import HTTPException

from .schemas import ProdutoEstoqueCreate, ProdutoEstoqueOut, ProdutoEstoqueUpdate

_ALLOWED_SORT_FIELDS = {"quantidade", "$createdAt"}
_ALLOWED_ORDER_VALUES = {"asc", "desc"}
_DEFAULT_LIMIT = 20


def _map(doc: Dict[str, Any]) -> ProdutoEstoqueOut:
    return ProdutoEstoqueOut(
        id=doc.get("$id"),
        catalogo_id=doc.get("catalogo_id", ""),
        venda_id=doc.get("venda_id", ""),
        quantidade=int(doc.get("quantidade", 0)),
        createdAt=doc.get("$createdAt", ""),
        updatedAt=doc.get("$updatedAt", ""),
    )


class ProdutosEstoqueService:
    def __init__(self, databases: Databases, database_id: str, collection_id: str) -> None:
        self._db = databases
        self._db_id = database_id
        self._col = collection_id

    async def _io(self, fn: Any, *a: Any, **kw: Any) -> Any:
        return await asyncio.to_thread(fn, *a, **kw)

    async def list(self, page: int, limit: int | None, q: str | None, sort: str | None, order: str | None) -> Dict[str, Any]:
        limit_v = limit or _DEFAULT_LIMIT
        off = (page - 1) * limit_v
        queries: List[Any] = [Query.limit(limit_v), Query.offset(off)]
        if sort:
            if sort not in _ALLOWED_SORT_FIELDS:
                raise HTTPException(400, "Campo de ordenação inválido.")
            if order and order not in _ALLOWED_ORDER_VALUES:
                raise HTTPException(400, "Ordem inválida.")
            queries.append(Query.order_desc(sort) if order == "desc" else Query.order_asc(sort))
        if q and q.strip():
            s = q.strip()
            queries.append(Query.or_([Query.search("catalogo_id", s), Query.search("venda_id", s)]))
        try:
            res = await self._io(self._db.list_documents, self._db_id, self._col, queries)
        except AppwriteException as e:
            raise HTTPException(e.code or 500, e.message) from e
        items = [_map(d).model_dump() for d in res.get("documents", [])]
        return {"items": items, "total": res.get("total", len(items))}

    async def get(self, item_id: str) -> ProdutoEstoqueOut:
        try:
            d = await self._io(self._db.get_document, self._db_id, self._col, item_id)
        except AppwriteException as e:
            if e.code == 404:
                raise HTTPException(404, "Item de estoque não encontrado.") from e
            raise HTTPException(e.code or 500, e.message) from e
        return _map(d)

    async def create(self, body: ProdutoEstoqueCreate) -> ProdutoEstoqueOut:
        data = body.model_dump(exclude_unset=True)
        try:
            d = await self._io(self._db.create_document, self._db_id, self._col, "unique()", data)
        except AppwriteException as e:
            raise HTTPException(e.code or 500, e.message) from e
        return _map(d)

    async def update(self, item_id: str, body: ProdutoEstoqueUpdate) -> ProdutoEstoqueOut:
        data = body.model_dump(exclude_unset=True)
        try:
            d = await self._io(self._db.update_document, self._db_id, self._col, item_id, data)
        except AppwriteException as e:
            if e.code == 404:
                raise HTTPException(404, "Item de estoque não encontrado.") from e
            raise HTTPException(e.code or 500, e.message) from e
        return _map(d)

    async def delete(self, item_id: str) -> None:
        try:
            await self._io(self._db.delete_document, self._db_id, self._col, item_id)
        except AppwriteException as e:
            if e.code == 404:
                raise HTTPException(404, "Item de estoque não encontrado.") from e
            raise HTTPException(e.code or 500, e.message) from e
