"""Dashboard tasks context view/filter/sorting tests."""

from __future__ import annotations

from datetime import datetime, timedelta

from app.services import dashboard_service


def _today() -> datetime:
    return datetime.now().astimezone()


def test_tasks_context_prioritizes_overdue_then_today_then_upcoming(monkeypatch):
    now = _today().date()
    overdue = (now - timedelta(days=1)).isoformat()
    today = now.isoformat()
    upcoming = (now + timedelta(days=2)).isoformat()

    sample = [
        {"id": "future", "provider": "todoist", "content": "future", "due": {"date": upcoming}},
        {"id": "nodue", "provider": "todoist", "content": "nodue"},
        {"id": "today", "provider": "todoist", "content": "today", "due": {"date": today}},
        {"id": "overdue", "provider": "todoist", "content": "overdue", "due": {"date": overdue}},
    ]

    monkeypatch.setattr(dashboard_service.integrations_service, "list_tasks", lambda **_: sample)
    context = dashboard_service.get_tasks_context(task_view="all", show_completed=False)

    assert [item["id"] for item in context["tasks"]] == ["overdue", "today", "future", "nodue"]


def test_tasks_context_today_view_includes_overdue_and_today_only(monkeypatch):
    now = _today().date()
    overdue = (now - timedelta(days=3)).isoformat()
    today = now.isoformat()
    upcoming = (now + timedelta(days=1)).isoformat()

    sample = [
        {"id": "overdue", "provider": "todoist", "content": "overdue", "due": {"date": overdue}},
        {"id": "today", "provider": "todoist", "content": "today", "due": {"date": today}},
        {"id": "future", "provider": "todoist", "content": "future", "due": {"date": upcoming}},
    ]

    monkeypatch.setattr(dashboard_service.integrations_service, "list_tasks", lambda **_: sample)
    context = dashboard_service.get_tasks_context(task_view="today", show_completed=False)

    assert [item["id"] for item in context["tasks"]] == ["overdue", "today"]


def test_tasks_context_hides_completed_unless_requested(monkeypatch):
    now = _today().date().isoformat()
    sample = [
        {"id": "open", "provider": "todoist", "content": "open", "due": {"date": now}, "completed": False},
        {"id": "done", "provider": "todoist", "content": "done", "due": {"date": now}, "completed": True},
    ]

    monkeypatch.setattr(dashboard_service.integrations_service, "list_tasks", lambda **_: sample)

    hidden = dashboard_service.get_tasks_context(task_view="all", show_completed=False)
    shown = dashboard_service.get_tasks_context(task_view="all", show_completed=True)

    assert [item["id"] for item in hidden["tasks"]] == ["open"]
    assert [item["id"] for item in shown["tasks"]] == ["open", "done"]
