"""Performance regression tests: budget category item_count annotation."""

import pytest
from django.contrib.auth import get_user_model
from django.db import connection
from django.test.utils import CaptureQueriesContext
from rest_framework.test import APIClient

from apps.finance.models import BudgetCategory, BudgetItem

User = get_user_model()


@pytest.fixture
def client(db):
    admin = User.objects.create_superuser(email="admin@test.local", password="x")
    c = APIClient()
    c.force_authenticate(admin)
    return c


def _rows(resp):
    body = resp.json()
    return body["results"] if isinstance(body, dict) and "results" in body else body


@pytest.mark.django_db
class TestBudgetCategoryItemCount:
    def test_counts_correct(self, client):
        a = BudgetCategory.objects.create(code="A", name="Salaries")
        BudgetCategory.objects.create(code="B", name="Empty")
        BudgetItem.objects.create(category=a, code="A.1", name="i1")
        BudgetItem.objects.create(category=a, code="A.2", name="i2")

        rows = {r["code"]: r for r in _rows(client.get("/api/budget-categories/"))}
        assert rows["A"]["item_count"] == 2
        assert rows["B"]["item_count"] == 0

    def test_queries_constant_in_rows(self, client):
        BudgetCategory.objects.create(code="C0", name="c0")
        with CaptureQueriesContext(connection) as small:
            client.get("/api/budget-categories/")
        for i in range(1, 7):
            cat = BudgetCategory.objects.create(code=f"C{i}", name=f"c{i}")
            BudgetItem.objects.create(category=cat, code=f"C{i}.1", name="x")
        with CaptureQueriesContext(connection) as big:
            client.get("/api/budget-categories/")
        assert len(big.captured_queries) == len(small.captured_queries)
