"""Department employee_count: correct values, cached GROUP BY."""

import pytest
from django.contrib.auth import get_user_model
from django.core.cache import cache
from rest_framework.test import APIClient

from apps.companies.models import Department

User = get_user_model()


@pytest.fixture(autouse=True)
def clear_cache():
    cache.clear()
    yield
    cache.clear()


@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 TestDeptCounts:
    def test_employee_count_correct(self, client):
        from apps.hr.models import Employee
        Department.objects.create(name="Engineering")
        Department.objects.create(name="Empty Dept")
        # Signal auto-creates an Employee per user; route them to Engineering.
        u = User.objects.create_user(email="e1@test.local", password="x")
        Employee.objects.filter(user=u).update(department="Engineering")

        rows = {r["name"]: r for r in _rows(client.get("/api/departments/"))}
        assert rows["Engineering"]["employee_count"] == 1
        assert rows["Empty Dept"]["employee_count"] == 0

    def test_counts_cached_across_requests(self, client):
        from apps.hr.models import Employee
        Department.objects.create(name="Ops")
        client.get("/api/departments/")  # warms dept_counts cache
        u = User.objects.create_user(email="e2@test.local", password="x")
        Employee.objects.filter(user=u).update(department="Ops")

        # Still 0: served from the 60s cache.
        rows = {r["name"]: r for r in _rows(client.get("/api/departments/"))}
        assert rows["Ops"]["employee_count"] == 0
        cache.delete("dept_counts")
        rows = {r["name"]: r for r in _rows(client.get("/api/departments/"))}
        assert rows["Ops"]["employee_count"] == 1
