"""Tests for /api/timeline router."""

from unittest.mock import AsyncMock

import pytest
from fastapi.testclient import TestClient

from hangar.dependencies import get_timeline_service
from hangar.main import app
from hangar.models.timeline import TimelineEvent, TimelineResponse


def _mock_timeline_service() -> AsyncMock:
    """Create a mock TimelineService."""
    service = AsyncMock()
    service.get_timeline.return_value = TimelineResponse(
        events=[
            TimelineEvent(
                event_type="closed",
                task_id="hangar-abc",
                task_title="Test task",
                timestamp="2026-02-07T12:00:00+01:00",
                close_reason="Shipped it!",
            ),
            TimelineEvent(
                event_type="created",
                task_id="hangar-abc",
                task_title="Test task",
                timestamp="2026-02-07T10:00:00+01:00",
            ),
        ],
        total_events=2,
    )
    return service


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


def test_get_timeline(client: TestClient) -> None:
    """GET /api/timeline should return events."""
    response = client.get("/api/timeline")
    assert response.status_code == 200
    data = response.json()
    assert data["total_events"] == 2
    assert len(data["events"]) == 2
    assert data["events"][0]["event_type"] == "closed"
    assert data["events"][0]["close_reason"] == "Shipped it!"


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