"""Tests for /api/stats router."""

from unittest.mock import AsyncMock

import pytest
from fastapi.testclient import TestClient

from hangar.dependencies import get_stats_service
from hangar.main import app
from hangar.models.stats import EpicStats, ProjectStats


def _mock_stats_service() -> AsyncMock:
    """Create a mock StatsService."""
    service = AsyncMock()
    service.get_stats.return_value = ProjectStats(
        total_tasks=10,
        closed_tasks=7,
        in_progress_tasks=2,
        open_tasks=1,
        completion_rate=70.0,
        avg_lead_time_hours=4.5,
        time_span_days=3.0,
        throughput_per_day=2.33,
        epic_stats=[
            EpicStats(
                epic_id="epic-1",
                epic_title="My Epic",
                task_count=5,
                closed_count=5,
                time_span_days=1.5,
            ),
        ],
    )
    return service


@pytest.fixture(autouse=True)
def _override_deps():
    """Override StatsService dependency for all tests."""
    mock = _mock_stats_service()
    app.dependency_overrides[get_stats_service] = lambda: mock
    yield mock
    app.dependency_overrides.clear()


def test_get_stats(client: TestClient) -> None:
    """GET /api/stats should return project statistics."""
    response = client.get("/api/stats")
    assert response.status_code == 200
    data = response.json()
    assert data["total_tasks"] == 10
    assert data["closed_tasks"] == 7
    assert data["completion_rate"] == 70.0
    assert data["throughput_per_day"] == 2.33
    assert len(data["epic_stats"]) == 1
    assert data["epic_stats"][0]["epic_id"] == "epic-1"


def test_stats_service_error(client: TestClient) -> None:
    """GET /api/stats should return 502 on service error."""
    mock = AsyncMock()
    mock.get_stats.side_effect = RuntimeError("bd list failed")
    app.dependency_overrides[get_stats_service] = lambda: mock
    response = client.get("/api/stats")
    assert response.status_code == 502
