import pytest
import sys
from pathlib import Path

# Add parent of db_core to path
parent_dir = Path(__file__).parent.parent.parent
if str(parent_dir) not in sys.path:
    sys.path.insert(0, str(parent_dir))

from db_core.clients.postgresql import PostgresClient
from db_core.query import QuerySet

pytestmark = pytest.mark.pg


@pytest.mark.asyncio
async def test_queryset_count(db_client: PostgresClient):
    """Test count method"""
    result = await db_client.table("users").get()
    assert result.count() == 4


@pytest.mark.asyncio
async def test_queryset_all(db_client: PostgresClient):
    """Test all method returns list"""
    result = await db_client.table("users").get()
    all_users = result.all()
    assert isinstance(all_users, list)
    assert len(all_users) == 4


@pytest.mark.asyncio
async def test_queryset_first_with_data(db_client: PostgresClient):
    """Test first method with data"""
    result = await db_client.table("users").order_by("name").get()
    first = result.first()
    assert first is not None
    assert first["name"] == "Alice Smith"


@pytest.mark.asyncio
async def test_queryset_first_empty(db_client: PostgresClient):
    """Test first method with no data"""
    result = await db_client.table("users").where("id", -1).get()
    first = result.first()
    assert first is None


@pytest.mark.asyncio
async def test_queryset_one_success(db_client: PostgresClient):
    """Test one method with exactly one result"""
    result = await db_client.table("users").where("email", "alice@example.com").get()
    user = result.one()
    assert user["name"] == "Alice Smith"


@pytest.mark.asyncio
async def test_queryset_remove_aliases_delete():
    """Test remove() calls delete() and returns delete count"""
    class DummyClient:
        def __init__(self):
            self.called = False

        async def _bulk_delete(self, table, ids):
            self.called = True
            assert table == "users"
            assert ids == [1, 2]
            return len(ids)

    result = QuerySet(rows=[{"id": 1}, {"id": 2}], client=DummyClient(), table="users")
    deleted = await result.remove()
    assert deleted == 2
    assert result.client.called


@pytest.mark.asyncio
async def test_queryset_rows_attribute(db_client: PostgresClient):
    """Test direct access to rows"""
    result = await db_client.table("users").limit(2).get()
    assert hasattr(result, "rows")
    assert len(result.rows) == 2
    assert isinstance(result.rows, list)
