"""
Integration and unit tests for Dashboard & Analytics endpoints, services, and caching.
Covers:
- Empty state metrics (zeroes/empty lists)
- Aggregation accuracy (operational funnel, financial ledgers, tender breakdown, commissions)
- Daily contiguous time-series trends
- Top performers ranking (tests, packages, referrers)
- Date range validation (start > end raises 422)
- Multi-branch tenant isolation and Superadmin consolidation
- 5-minute Redis caching and ?refresh=true cache busting
- RBAC permission enforcement (401 and 403)
"""

from datetime import UTC, date, datetime, timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo

import pytest
import pytest_asyncio
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.security import create_access_token, hash_password
from app.models.appointment import Appointment, AppointmentSlot, AppointmentStatus, BookingChannel
from app.models.billing import Bill, BillStatus, Payment, PaymentMode
from app.models.lab import Lab
from app.models.order import OrderPackage, OrderStatus, OrderTest, Sample, SampleStatus, VisitOrder
from app.models.package import TestPackage as LabTestPackage
from app.models.patient import Gender, Patient
from app.models.referral import CommissionEntry, Referral, ReferralType
from app.models.report import Report, ReportStatus
from app.models.test import (
    Test as LabTest,
)
from app.models.test import (
    TestCategory as LabTestCategory,
)
from app.models.test import (
    TestResultType as LabTestResultType,
)
from app.models.user import User, UserRole
from app.repositories.permission_repository import PermissionRepository


@pytest.fixture(autouse=True)
def isolated_dashboard_cache(monkeypatch: pytest.MonkeyPatch) -> None:
    """Each test gets its own cache; cache-hit and refresh behavior stay enabled."""
    from app.services import dashboard_service

    cached = {}

    async def get_cached(key):
        return cached.get(key)

    async def store_cached(key, value, expires_in_seconds=300):
        cached[key] = value

    monkeypatch.setattr(dashboard_service, "get_dashboard_cache", get_cached)
    monkeypatch.setattr(dashboard_service, "store_dashboard_cache", store_cached)


@pytest_asyncio.fixture(autouse=True)
async def seed_perms(db_session: AsyncSession) -> None:
    """Seed permissions for RBAC checks."""
    repo = PermissionRepository()
    await repo.seed_permissions(db_session)


@pytest_asyncio.fixture
async def test_lab(db_session: AsyncSession) -> Lab:
    """Create test laboratory branch A."""
    lab = Lab(name="Munal Central Branch", address="Tripureshwor, Kathmandu")
    db_session.add(lab)
    await db_session.commit()
    await db_session.refresh(lab)
    return lab


@pytest_asyncio.fixture
async def branch_b(db_session: AsyncSession) -> Lab:
    """Create test laboratory branch B."""
    lab = Lab(name="Munal Lalitpur Branch", address="Jawalakhel, Lalitpur")
    db_session.add(lab)
    await db_session.commit()
    await db_session.refresh(lab)
    return lab


@pytest_asyncio.fixture
async def admin_user(db_session: AsyncSession, test_lab: Lab) -> tuple[User, str]:
    """Create admin user assigned to branch A."""
    user = User(
        lab_id=test_lab.id,
        name="Branch Admin",
        phone="9841000010",
        email="admin_a@munal.test",
        role=UserRole.SUPERADMIN,
        hashed_password=hash_password("Pass123!"),
        is_active=True,
    )
    db_session.add(user)
    await db_session.commit()
    await db_session.refresh(user)
    token = create_access_token(
        subject=str(user.id),
        extra_claims={"email": user.email, "role": user.role.value, "lab_id": str(user.lab_id)},
    )
    return user, token


@pytest_asyncio.fixture
async def branch_b_user(db_session: AsyncSession, branch_b: Lab) -> tuple[User, str]:
    """Create receptionist/staff user assigned to branch B."""
    user = User(
        lab_id=branch_b.id,
        name="Branch B Receptionist",
        phone="9841000011",
        email="staff_b@munal.test",
        role=UserRole.RECEPTIONIST,
        hashed_password=hash_password("Pass123!"),
        is_active=True,
    )
    db_session.add(user)
    await db_session.commit()
    await db_session.refresh(user)
    token = create_access_token(
        subject=str(user.id),
        extra_claims={"email": user.email, "role": user.role.value, "lab_id": str(user.lab_id)},
    )
    return user, token


@pytest_asyncio.fixture
async def superadmin_user(db_session: AsyncSession, test_lab: Lab) -> tuple[User, str]:
    """Create superadmin user with cross-branch authority."""
    user = User(
        lab_id=test_lab.id,
        name="Super Admin",
        phone="9841000012",
        email="superadmin@munal.test",
        role=UserRole.SUPERADMIN,
        hashed_password=hash_password("Pass123!"),
        is_active=True,
    )
    db_session.add(user)
    await db_session.commit()
    await db_session.refresh(user)
    token = create_access_token(
        subject=str(user.id),
        extra_claims={"email": user.email, "role": user.role.value, "lab_id": str(user.lab_id)},
    )
    return user, token


# ─────────────────────────────────────────────────────────────────────────────
# 1. Access Control & Validation Tests
# ─────────────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_dashboard_unauthorized(client: AsyncClient) -> None:
    """Requests without JWT tokens receive 401 Unauthorized."""
    resp = await client.get("/api/v1/dashboard/overview")
    assert resp.status_code == 401
    assert resp.json()["success"] is False


@pytest.mark.asyncio
async def test_dashboard_date_validation(
    client: AsyncClient,
    admin_user: tuple[User, str],
) -> None:
    """Supplying start_date greater than end_date yields 422 Unprocessable Entity."""
    _, token = admin_user
    today = date.today()
    future = today + timedelta(days=10)

    resp = await client.get(
        "/api/v1/dashboard/overview",
        params={"start_date": future.isoformat(), "end_date": today.isoformat()},
        headers={"Authorization": f"Bearer {token}"},
    )
    assert resp.status_code == 422
    assert "cannot be after" in resp.json()["error"]["message"]


@pytest.mark.asyncio
async def test_dashboard_empty_state(
    client: AsyncClient,
    admin_user: tuple[User, str],
) -> None:
    """Empty database returns 0s and empty lists cleanly without crashing."""
    _, token = admin_user
    headers = {"Authorization": f"Bearer {token}"}

    # 1. Overview
    resp_overview = await client.get("/api/v1/dashboard/overview", headers=headers)
    assert resp_overview.status_code == 200
    ov_data = resp_overview.json()["data"]
    assert ov_data["operational"]["total_patients"] == 0
    assert Decimal(ov_data["financial"]["total_invoiced"]) == Decimal("0.00")
    assert len(ov_data["trend"]) >= 30  # trailing 30 days contiguous points
    assert ov_data["top_tests"] == []

    # 2. Operational
    resp_op = await client.get("/api/v1/dashboard/operational", headers=headers)
    assert resp_op.status_code == 200
    assert resp_op.json()["data"]["total_orders"] == 0

    # 3. Financial
    resp_fin = await client.get("/api/v1/dashboard/financial", headers=headers)
    assert resp_fin.status_code == 200
    assert Decimal(resp_fin.json()["data"]["total_collected"]) == Decimal("0.00")

    # 4. Trends
    resp_trends = await client.get("/api/v1/dashboard/trends", headers=headers)
    assert resp_trends.status_code == 200
    assert isinstance(resp_trends.json()["data"], list)

    # 5. Top Performers
    resp_top = await client.get("/api/v1/dashboard/top-performers", headers=headers)
    assert resp_top.status_code == 200
    assert resp_top.json()["data"]["top_tests"] == []
    assert resp_top.json()["data"]["top_packages"] == []
    assert resp_top.json()["data"]["top_referrers"] == []


# ─────────────────────────────────────────────────────────────────────────────
# 2. Aggregation & Business Rules Tests
# ─────────────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_dashboard_operational_stats_accuracy(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_user: tuple[User, str],
    test_lab: Lab,
) -> None:
    """Verify operational metrics correctly count patients, orders by status, and backlogs."""
    _, token = admin_user
    headers = {"Authorization": f"Bearer {token}"}

    # Create 2 patients
    p1 = Patient(
        lab_id=test_lab.id,
        patient_code="P/26/0000000001",
        name="Aakash Thapa",
        gender=Gender.MALE,
        age=30,
        phone="9841111111",
    )
    p2 = Patient(
        lab_id=test_lab.id,
        patient_code="P/26/0000000002",
        name="Bina Sharma",
        gender=Gender.FEMALE,
        age=25,
        phone="9841111112",
    )
    db_session.add_all([p1, p2])
    await db_session.commit()
    await db_session.refresh(p1)
    await db_session.refresh(p2)

    # Create 2 orders: 1 pending, 1 completed
    o1 = VisitOrder(
        lab_id=test_lab.id,
        patient_id=p1.id,
        order_number="ORD-26-0001",
        status=OrderStatus.PENDING,
    )
    o2 = VisitOrder(
        lab_id=test_lab.id,
        patient_id=p2.id,
        order_number="ORD-26-0002",
        status=OrderStatus.COMPLETED,
    )
    db_session.add_all([o1, o2])
    await db_session.commit()
    await db_session.refresh(o1)
    await db_session.refresh(o2)

    # Create 1 sample with PENDING status
    s1 = Sample(
        lab_id=test_lab.id,
        order_id=o1.id,
        sample_code="SMP-001",
        barcode="SAM-20260920-000001",
        sample_type="Blood",
        status=SampleStatus.PENDING,
    )
    # Create 1 sample with COLLECTED status
    s2 = Sample(
        lab_id=test_lab.id,
        order_id=o2.id,
        sample_code="SMP-002",
        barcode="SAM-20260920-000002",
        sample_type="Blood",
        status=SampleStatus.COLLECTED,
    )
    db_session.add_all([s1, s2])

    # Create 1 report in DRAFT verification status
    r1 = Report(
        order_id=o1.id,
        status=ReportStatus.DRAFT,
    )
    db_session.add(r1)

    # Create today's appointment
    apt = Appointment(
        lab_id=test_lab.id,
        patient_id=p1.id,
        status=AppointmentStatus.CONFIRMED,
        booked_via=BookingChannel.PORTAL,
    )
    db_session.add(apt)
    await db_session.commit()

    # A booking created today for a future slot must not count as today's arrival.
    tomorrow = datetime.now(ZoneInfo("Asia/Kathmandu")) + timedelta(days=1)
    future_slot = AppointmentSlot(
        lab_id=test_lab.id,
        start_at=tomorrow,
        end_at=tomorrow + timedelta(hours=1),
        capacity=10,
    )
    db_session.add(future_slot)
    await db_session.flush()
    db_session.add(
        Appointment(
            lab_id=test_lab.id,
            patient_id=p1.id,
            slot_id=future_slot.id,
            status=AppointmentStatus.CONFIRMED,
            booked_via=BookingChannel.PORTAL,
        )
    )
    await db_session.commit()

    # Query operational stats
    resp = await client.get("/api/v1/dashboard/operational", headers=headers)
    assert resp.status_code == 200
    data = resp.json()["data"]

    assert data["total_patients"] == 2
    assert data["new_patients_period"] == 2
    assert data["total_orders"] == 2
    assert data["orders_by_status"].get("pending") == 1
    assert data["orders_by_status"].get("completed") == 1
    assert data["pending_samples"] == 1
    assert data["pending_verifications"] == 1
    assert data["today_appointments"] == 1


@pytest.mark.asyncio
async def test_dashboard_financial_stats_excludes_void_bills(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_user: tuple[User, str],
    test_lab: Lab,
) -> None:
    """Financial calculations must strictly exclude VOID bills and calculate split tenders."""
    _, token = admin_user
    headers = {"Authorization": f"Bearer {token}"}

    # Patient
    pat = Patient(
        lab_id=test_lab.id,
        patient_code="P/26/0000000003",
        name="Chandra Giri",
        gender=Gender.MALE,
        age=45,
        phone="9841111113",
    )
    db_session.add(pat)
    await db_session.commit()
    await db_session.refresh(pat)

    order = VisitOrder(
        lab_id=test_lab.id,
        patient_id=pat.id,
        order_number="ORD-26-0003A",
        status=OrderStatus.COMPLETED,
    )
    order_void = VisitOrder(
        lab_id=test_lab.id,
        patient_id=pat.id,
        order_number="ORD-26-0003B",
        status=OrderStatus.CANCELLED,
    )
    db_session.add_all([order, order_void])
    await db_session.commit()
    await db_session.refresh(order)
    await db_session.refresh(order_void)

    # Active Bill: Total 1000, Paid 700, Due 300, Discount 100
    active_bill = Bill(
        lab_id=test_lab.id,
        patient_id=pat.id,
        order_id=order.id,
        bill_number="INV/26/000001",
        status=BillStatus.PARTIAL,
        subtotal=Decimal("1100.00"),
        discount_amount=Decimal("100.00"),
        total_amount=Decimal("1000.00"),
        paid_amount=Decimal("700.00"),
        due_amount=Decimal("300.00"),
    )
    # Void Bill: Total 5000, Paid 5000 (must NOT be counted)
    void_bill = Bill(
        lab_id=test_lab.id,
        patient_id=pat.id,
        order_id=order_void.id,
        bill_number="INV/26/000002",
        status=BillStatus.VOID,
        subtotal=Decimal("5000.00"),
        discount_amount=Decimal("0.00"),
        total_amount=Decimal("5000.00"),
        paid_amount=Decimal("5000.00"),
        due_amount=Decimal("0.00"),
    )
    db_session.add_all([active_bill, void_bill])
    await db_session.commit()
    await db_session.refresh(active_bill)
    await db_session.refresh(void_bill)

    # Payments for active bill: 400 CASH, 300 ESEWA
    pay1 = Payment(
        lab_id=test_lab.id,
        bill_id=active_bill.id,
        amount=Decimal("400.00"),
        payment_mode=PaymentMode.CASH,
        paid_at=datetime.now(UTC),
    )
    pay2 = Payment(
        lab_id=test_lab.id,
        bill_id=active_bill.id,
        amount=Decimal("300.00"),
        payment_mode=PaymentMode.CARD,
        paid_at=datetime.now(UTC),
    )
    # Payment for void bill: 5000 TRANSFER (must NOT be counted)
    pay_void = Payment(
        lab_id=test_lab.id,
        bill_id=void_bill.id,
        amount=Decimal("5000.00"),
        payment_mode=PaymentMode.TRANSFER,
        paid_at=datetime.now(UTC),
    )
    db_session.add_all([pay1, pay2, pay_void])

    # Referral and commission entries
    ref = Referral(
        lab_id=test_lab.id,
        name="Dr. Roshan KC",
        referral_type=ReferralType.DOCTOR,
        phone="9841888888",
        commission_rate=Decimal("10.00"),
    )
    db_session.add(ref)
    await db_session.commit()
    await db_session.refresh(ref)

    # Commission 1: 50.00 settled
    comm_settled = CommissionEntry(
        lab_id=test_lab.id,
        referral_id=ref.id,
        order_id=order.id,
        order_amount=Decimal("500.00"),
        commission_rate=Decimal("10.00"),
        commission_amount=Decimal("50.00"),
        is_settled=True,
    )
    # Commission 2: 70.00 unsettled
    comm_unsettled = CommissionEntry(
        lab_id=test_lab.id,
        referral_id=ref.id,
        order_id=order_void.id,
        order_amount=Decimal("700.00"),
        commission_rate=Decimal("10.00"),
        commission_amount=Decimal("70.00"),
        is_settled=False,
    )
    db_session.add_all([comm_settled, comm_unsettled])
    await db_session.commit()

    resp = await client.get("/api/v1/dashboard/financial", headers=headers)
    assert resp.status_code == 200
    data = resp.json()["data"]

    assert Decimal(data["total_invoiced"]) == Decimal("1000.00")
    assert Decimal(data["total_collected"]) == Decimal("700.00")
    assert Decimal(data["total_outstanding"]) == Decimal("300.00")
    assert Decimal(data["total_discounts"]) == Decimal("100.00")
    assert Decimal(data["revenue_by_tender"]["cash"]) == Decimal("400.00")
    assert Decimal(data["revenue_by_tender"]["card"]) == Decimal("300.00")
    assert "transfer" not in data["revenue_by_tender"]
    assert Decimal(data["accrued_commissions"]) == Decimal("120.00")
    assert Decimal(data["unsettled_commissions"]) == Decimal("70.00")

    invoice_day = active_bill.created_at.astimezone(ZoneInfo("Asia/Kathmandu")).date().isoformat()
    trends_resp = await client.get(
        "/api/v1/dashboard/trends",
        params={"start_date": invoice_day, "end_date": invoice_day},
        headers=headers,
    )
    assert trends_resp.status_code == 200
    daily_trend = trends_resp.json()["data"][0]
    assert Decimal(daily_trend["invoiced_amount"]) == Decimal("1000.00")
    assert daily_trend["invoice_count"] == 1
    assert Decimal(daily_trend["revenue"]) == Decimal("700.00")


@pytest.mark.asyncio
async def test_dashboard_top_performers_ranking(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_user: tuple[User, str],
    test_lab: Lab,
) -> None:
    """Verify ranking logic for top tests, top packages, and top referring doctors."""
    _, token = admin_user
    headers = {"Authorization": f"Bearer {token}"}

    # Setup test category and tests
    cat = LabTestCategory(lab_id=test_lab.id, name="General Pathology")
    db_session.add(cat)
    await db_session.commit()
    await db_session.refresh(cat)

    t1 = LabTest(
        lab_id=test_lab.id,
        category_id=cat.id,
        code="CBC",
        name="Complete Blood Count",
        price=Decimal("500.00"),
        result_type=LabTestResultType.NUMERIC,
    )
    t2 = LabTest(
        lab_id=test_lab.id,
        category_id=cat.id,
        code="LFT",
        name="Liver Function Test",
        price=Decimal("1200.00"),
        result_type=LabTestResultType.NUMERIC,
    )
    db_session.add_all([t1, t2])

    # Setup package
    pkg = LabTestPackage(
        lab_id=test_lab.id,
        code="WNP01",
        name="Comprehensive Executive Wellness",
        price=Decimal("3500.00"),
    )
    db_session.add(pkg)

    # Setup referrer
    doc = Referral(
        lab_id=test_lab.id,
        name="Dr. Sanduk Ruit",
        referral_type=ReferralType.DOCTOR,
        phone="9841223344",
        commission_rate=Decimal("15.00"),
    )
    db_session.add(doc)

    # Setup patient
    pat = Patient(
        lab_id=test_lab.id,
        patient_code="P/26/0000000004",
        name="Dinesh KC",
        gender=Gender.MALE,
        age=38,
        phone="9841111114",
    )
    db_session.add(pat)
    await db_session.commit()
    await db_session.refresh(t1)
    await db_session.refresh(t2)
    await db_session.refresh(pkg)
    await db_session.refresh(doc)
    await db_session.refresh(pat)

    # Order with CBC (2 times) and LFT (1 time)
    order1 = VisitOrder(lab_id=test_lab.id, patient_id=pat.id, order_number="ORD-26-0004")
    order2 = VisitOrder(lab_id=test_lab.id, patient_id=pat.id, order_number="ORD-26-0005")
    db_session.add_all([order1, order2])
    await db_session.commit()
    await db_session.refresh(order1)
    await db_session.refresh(order2)

    ot1 = OrderTest(order_id=order1.id, test_id=t1.id, price_at_order=Decimal("500.00"))
    ot2 = OrderTest(order_id=order2.id, test_id=t1.id, price_at_order=Decimal("500.00"))
    ot3 = OrderTest(order_id=order1.id, test_id=t2.id, price_at_order=Decimal("1200.00"))
    op1 = OrderPackage(order_id=order1.id, package_id=pkg.id, price_at_order=Decimal("3500.00"))
    db_session.add_all([ot1, ot2, ot3, op1])

    comm = CommissionEntry(
        lab_id=test_lab.id,
        referral_id=doc.id,
        order_id=order1.id,
        order_amount=Decimal("5700.00"),
        commission_rate=Decimal("15.00"),
        commission_amount=Decimal("855.00"),
    )
    db_session.add(comm)
    await db_session.commit()

    resp = await client.get("/api/v1/dashboard/top-performers", headers=headers)
    assert resp.status_code == 200
    data = resp.json()["data"]

    # CBC ordered 2 times, LFT ordered 1 time -> CBC is #1
    assert len(data["top_tests"]) == 2
    assert data["top_tests"][0]["code"] == "CBC"
    assert data["top_tests"][0]["count"] == 2
    assert Decimal(data["top_tests"][0]["total_value"]) == Decimal("1000.00")
    assert data["top_tests"][1]["code"] == "LFT"
    assert data["top_tests"][1]["count"] == 1

    # Package
    assert len(data["top_packages"]) == 1
    assert data["top_packages"][0]["code"] == "WNP01"
    assert data["top_packages"][0]["count"] == 1

    # Referrer
    assert len(data["top_referrers"]) == 1
    assert data["top_referrers"][0]["name"] == "Dr. Sanduk Ruit"
    assert Decimal(data["top_referrers"][0]["commission_earned"]) == Decimal("855.00")


# ─────────────────────────────────────────────────────────────────────────────
# 3. Branch Isolation & Superadmin Tests
# ─────────────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_dashboard_branch_isolation(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_user: tuple[User, str],
    branch_b_user: tuple[User, str],
    test_lab: Lab,
    branch_b: Lab,
) -> None:
    """Non-superadmin staff querying other branches receives 403 Forbidden."""
    _, token_b = branch_b_user

    # Branch B receptionist querying branch A explicitly
    resp = await client.get(
        "/api/v1/dashboard/overview",
        params={"lab_id": str(test_lab.id)},
        headers={"Authorization": f"Bearer {token_b}"},
    )
    assert resp.status_code == 403
    assert "other branches" in resp.json()["error"]["message"]


@pytest.mark.asyncio
async def test_dashboard_superadmin_consolidation(
    client: AsyncClient,
    db_session: AsyncSession,
    superadmin_user: tuple[User, str],
    test_lab: Lab,
    branch_b: Lab,
) -> None:
    """Superadmin can view org-wide consolidated metrics or target specific branches."""
    _, super_token = superadmin_user
    headers = {"Authorization": f"Bearer {super_token}"}

    # Add 1 patient in Branch A
    pa = Patient(
        lab_id=test_lab.id,
        patient_code="P/26/0000000010",
        name="Branch A Patient",
        gender=Gender.MALE,
        age=20,
        phone="9841111120",
    )
    # Add 2 patients in Branch B
    pb1 = Patient(
        lab_id=branch_b.id,
        patient_code="P/26/0000000011",
        name="Branch B Patient 1",
        gender=Gender.FEMALE,
        age=22,
        phone="9841111121",
    )
    pb2 = Patient(
        lab_id=branch_b.id,
        patient_code="P/26/0000000012",
        name="Branch B Patient 2",
        gender=Gender.MALE,
        age=24,
        phone="9841111122",
    )
    db_session.add_all([pa, pb1, pb2])
    await db_session.commit()

    # 1. Org-wide query (no lab_id filter)
    resp_org = await client.get("/api/v1/dashboard/operational", headers=headers)
    assert resp_org.status_code == 200
    assert resp_org.json()["data"]["total_patients"] == 3

    # 2. Scoped query to Branch A
    resp_a = await client.get(
        "/api/v1/dashboard/operational",
        params={"lab_id": str(test_lab.id)},
        headers=headers,
    )
    assert resp_a.status_code == 200
    assert resp_a.json()["data"]["total_patients"] == 1

    # 3. Scoped query to Branch B
    resp_b = await client.get(
        "/api/v1/dashboard/operational",
        params={"lab_id": str(branch_b.id)},
        headers=headers,
    )
    assert resp_b.status_code == 200
    assert resp_b.json()["data"]["total_patients"] == 2


# ─────────────────────────────────────────────────────────────────────────────
# 4. Redis Caching & Invalidation (?refresh=true)
# ─────────────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_dashboard_caching_and_refresh_invalidation(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_user: tuple[User, str],
    test_lab: Lab,
) -> None:
    """Verify 5-minute Redis caching holds metrics and ?refresh=true forces recomputation."""
    _, token = admin_user
    headers = {"Authorization": f"Bearer {token}"}

    # Step 1: Query initial operational stats -> 0 patients
    resp1 = await client.get("/api/v1/dashboard/operational", headers=headers)
    assert resp1.status_code == 200
    assert resp1.json()["data"]["total_patients"] == 0

    # Step 2: Add a patient directly to the database
    new_pat = Patient(
        lab_id=test_lab.id,
        patient_code="P/26/0000000050",
        name="Cache Test Patient",
        gender=Gender.MALE,
        age=29,
        phone="9841111150",
    )
    db_session.add(new_pat)
    await db_session.commit()

    # Step 3: Query without ?refresh=true -> hits Redis cache -> still returns 0
    resp2 = await client.get("/api/v1/dashboard/operational", headers=headers)
    assert resp2.status_code == 200
    assert resp2.json()["data"]["total_patients"] == 0

    # Step 4: Query with ?refresh=true -> bypasses cache -> reflects new patient count (1)
    resp3 = await client.get(
        "/api/v1/dashboard/operational",
        params={"refresh": "true"},
        headers=headers,
    )
    assert resp3.status_code == 200
    assert resp3.json()["data"]["total_patients"] == 1
