import asyncio
import os
import sys
from pathlib import Path

import pytest
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

os.environ.setdefault("APPWRITE_ENDPOINT", "http://localhost/v1")
os.environ.setdefault("APPWRITE_PROJECT_ID", "test-project")
os.environ.setdefault("APPWRITE_API_KEY", "test-key")

pytest.importorskip("appwrite")

from src.modules.produtos_venda.service import ProdutosVendaService  # noqa: E402


class _FakeDatabases:
    def __init__(self, documents):
        self._documents = documents
        self.last_queries = None

    def list_documents(self, database_id, collection_id, queries):
        self.last_queries = queries
        return {"documents": self._documents, "total": len(self._documents)}


def test_list_handles_null_strings() -> None:
    fake_db = _FakeDatabases(
        [
            {
                "$id": "doc1",
                "catalogo_id": None,
                "nome": None,
                "preco_venda": "42.5",
                "qtdade_estoque": None,
                "observacoes": None,
                "data_validade": None,
                "empresa_id": None,
                "$createdAt": None,
                "$updatedAt": None,
            }
        ]
    )

    service = ProdutosVendaService(fake_db, "db", "col")

    response = asyncio.run(
        service.list(page=1, limit=None, q=None, sort=None, order=None)
    )

    assert response["total"] == 1
    item = response["items"][0]
    assert item == {
        "id": "doc1",
        "catalogo_id": "",
        "nome": "",
        "preco_venda": 42.5,
        "preco_final": 47.6,
        "qtdade_estoque": 0,
        "observacoes": None,
        "data_validade": "",
        "empresa_id": None,
        "createdAt": "",
        "updatedAt": "",
    }


def test_list_converts_non_string_values_to_string() -> None:
    fake_db = _FakeDatabases(
        [
            {
                "$id": 123,
                "catalogo_id": 456,
                "nome": "Produto",
                "preco_venda": 10,
                "qtdade_estoque": 12,
                "observacoes": 789,
                "data_validade": "2024-05-01",
                "empresa_id": 1011,
                "$createdAt": "2024-01-01T00:00:00.000Z",
                "$updatedAt": "2024-01-02T00:00:00.000Z",
            }
        ]
    )

    service = ProdutosVendaService(fake_db, "db", "col")

    response = asyncio.run(
        service.list(page=1, limit=None, q=None, sort=None, order=None)
    )

    assert response["total"] == 1
    item = response["items"][0]
    assert item == {
        "id": "123",
        "catalogo_id": "456",
        "nome": "Produto",
        "preco_venda": 10.0,
        "preco_final": 11.2,
        "qtdade_estoque": 12,
        "observacoes": "789",
        "data_validade": "2024-05-01",
        "empresa_id": "1011",
        "createdAt": "2024-01-01T00:00:00.000Z",
        "updatedAt": "2024-01-02T00:00:00.000Z",
    }


def test_list_includes_empresa_id_filter() -> None:
    fake_db = _FakeDatabases([])
    service = ProdutosVendaService(fake_db, "db", "col")

    asyncio.run(
        service.list(
            page=1,
            limit=None,
            q=None,
            sort=None,
            order=None,
            empresa_id="empresa-123",
        )
    )

    assert fake_db.last_queries is not None
    assert any(
        '"attribute":"empresa_id"' in query and '"values":["empresa-123"]' in query
        for query in fake_db.last_queries
    )
