"""GET /api/dashboard/kpis: Auth + interne Aufruf-Hilfen."""
from __future__ import annotations

import os
from unittest.mock import patch

import pytest
from fastapi import Query
from fastapi.testclient import TestClient

os.environ.setdefault("SKIP_DB_MIGRATE", "1")

from fastapi_param_unwrap import unwrap_query_default
from main import app
from tenant_context import TenantContext, get_tenant_context


@pytest.fixture
def client() -> TestClient:
    return TestClient(app)


def test_unwrap_query_default_for_direct_route_calls() -> None:
    assert unwrap_query_default(Query(default=None)) is None
    assert unwrap_query_default("2026-01-01") == "2026-01-01"
    assert unwrap_query_default(7) == 7


def test_dashboard_kpis_unauthenticated_401(client: TestClient) -> None:
    r = client.get("/api/dashboard/kpis")
    assert r.status_code == 401


def _fake_tenant_for_kpis() -> TenantContext:
    return TenantContext(
        profile_id=42,
        global_role="trainer",
        effective_club_id=7,
        club_ids=frozenset({7}),
        memberships=[],
    )


@patch("routers.dashboard.list_training_units")
@patch("routers.dashboard.list_exercises_like_get")
def test_dashboard_kpis_200_when_inner_lists_mocked(
    mock_list_ex: object,
    mock_list_tu: object,
    client: TestClient,
) -> None:
    mock_list_ex.return_value = []
    mock_list_tu.return_value = []
    app.dependency_overrides[get_tenant_context] = _fake_tenant_for_kpis
    try:
        r = client.get("/api/dashboard/kpis")
        assert r.status_code == 200, r.text
        data = r.json()
        assert "year" in data
        assert data["draft_count"] == 0
        assert data["mine_count"] == 0
        assert data["ytd_completed_count"] == 0
        th = data["training_home"]
        assert th["upcoming"] == []
        assert th["planned_with_notes"] == []
        assert th["review_pending"] == []
        assert mock_list_ex.call_count == 2
        assert mock_list_tu.call_count == 3
    finally:
        app.dependency_overrides.clear()
