from __future__ import annotations

import asyncio

from appwrite.exception import AppwriteException
from appwrite.query import Query
from fastapi import HTTPException, status

from src.core.appwrite_client import get_appwrite_clients
from src.core.config import get_settings


async def assert_user_in_company(user_id: str, empresa_id: str) -> None:
    """Garante que o usuário informado possua vínculo com a empresa informada."""
    normalized_user = (user_id or "").strip()
    normalized_empresa = (empresa_id or "").strip()

    if not normalized_user or not normalized_empresa:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Usuário sem vínculo com a empresa informada.",
        )

    settings = get_settings()
    _, databases = get_appwrite_clients()

    queries = [
        Query.equal("usuarios", normalized_user),
        Query.equal("empresas-dados", normalized_empresa),
    ]

    try:
        response = await asyncio.to_thread(
            databases.list_documents,
            settings.appwrite_database_id,
            settings.appwrite_collection_usuario_empresa_perfis_id,
            queries,
        )
    except AppwriteException as exc:  # pragma: no cover - depende do Appwrite
        raise HTTPException(status_code=exc.code or 500, detail=exc.message) from exc

    if not response.get("total"):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Usuário sem vínculo com a empresa informada.",
        )
