"""GET /api/exercises: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
from __future__ import annotations

import os

import pytest
from fastapi.testclient import TestClient

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

from auth import require_auth
from main import app
from tenant_context import TenantContext, get_tenant_context


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


@pytest.fixture(autouse=True)
def _clear_overrides() -> None:
    yield
    app.dependency_overrides.pop(require_auth, None)
    app.dependency_overrides.pop(get_tenant_context, None)


def test_list_exercises_keyset_incomplete_returns_400(client: TestClient) -> None:
    app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
    app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
        profile_id=1,
        global_role="trainer",
        effective_club_id=None,
        club_ids=frozenset(),
        memberships=[],
    )
    r = client.get(
        "/api/exercises",
        params={"cursor_id": "42"},
        headers={"X-Auth-Token": "test"},
    )
    assert r.status_code == 400
    assert "cursor_updated_at" in r.json().get("detail", "").lower()


def test_list_exercises_keyset_with_offset_returns_400(client: TestClient) -> None:
    app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
    app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
        profile_id=1,
        global_role="trainer",
        effective_club_id=None,
        club_ids=frozenset(),
        memberships=[],
    )
    r = client.get(
        "/api/exercises",
        params={
            "cursor_id": "1",
            "cursor_updated_at": "2026-01-01T12:00:00.000Z",
            "offset": "10",
        },
        headers={"X-Auth-Token": "test"},
    )
    assert r.status_code == 400
    assert "offset" in r.json().get("detail", "").lower()


def test_list_exercises_keyset_bad_timestamp_returns_400(client: TestClient) -> None:
    app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
    app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
        profile_id=1,
        global_role="trainer",
        effective_club_id=None,
        club_ids=frozenset(),
        memberships=[],
    )
    r = client.get(
        "/api/exercises",
        params={"cursor_id": "1", "cursor_updated_at": "not-a-date"},
        headers={"X-Auth-Token": "test"},
    )
    assert r.status_code == 400
