"""Unit tests for document upsert operation."""

import httpx
import pytest
import respx

from pinecone._internal.http import HTTPClient, HTTPConfig
from pinecone.index.documents import Documents


@respx.mock
def test_upsert_success():
    """Test successful document upsert."""
    respx.post("https://test.io/namespaces/my-ns/documents/upsert").mock(
        return_value=httpx.Response(200, json={"upserted_count": 2})
    )

    client = HTTPClient(api_key="test", config=HTTPConfig(http2=False))
    documents = Documents(http=client, base_url="https://test.io")

    response = documents.upsert(
        namespace="my-ns",
        documents=[
            {"_id": "doc1", "title": "Hello"},
            {"_id": "doc2", "title": "World"},
        ],
    )

    assert response.upserted_count == 2


@respx.mock
def test_upsert_validates_empty_namespace():
    """Test that empty namespace raises ValueError."""
    client = HTTPClient(api_key="test", config=HTTPConfig(http2=False))
    documents = Documents(http=client, base_url="https://test.io")

    with pytest.raises(ValueError, match="namespace"):
        documents.upsert(namespace="", documents=[{"_id": "doc1"}])


@respx.mock
def test_upsert_validates_empty_documents():
    """Test that empty documents list raises ValueError."""
    client = HTTPClient(api_key="test", config=HTTPConfig(http2=False))
    documents = Documents(http=client, base_url="https://test.io")

    with pytest.raises(ValueError, match="documents must not be empty"):
        documents.upsert(namespace="my-ns", documents=[])


@respx.mock
def test_upsert_validates_missing_id():
    """Test that document without _id raises ValueError."""
    client = HTTPClient(api_key="test", config=HTTPConfig(http2=False))
    documents = Documents(http=client, base_url="https://test.io")

    with pytest.raises(ValueError, match="missing required '_id' field"):
        documents.upsert(namespace="my-ns", documents=[{"title": "No ID"}])
