"""Smoke-тесты M0: health, защита API, redirect OAuth-флоу."""

from fastapi.testclient import TestClient

from app.config import get_settings
from app.main import app

client = TestClient(app)


def test_health() -> None:
    assert client.get("/api/health").json() == {"status": "ok"}


def test_auth_me_requires_auth() -> None:
    assert client.get("/auth/me").status_code == 401


def test_login_redirects_to_sso() -> None:
    base_url = get_settings().gauth_base_url
    resp = client.get("/auth/login", follow_redirects=False)
    assert resp.status_code in (302, 307)
    location = resp.headers["location"]
    assert location.startswith(base_url)
    assert "state=" in location and "code_challenge=" in location


def test_api_requires_auth() -> None:
    """Регрессия: все /api эндпоинты должны требовать сессию."""
    from app.dependencies import require_user

    saved = app.dependency_overrides.pop(require_user, None)
    try:
        with TestClient(app) as c:
            assert c.get("/api/tasks").status_code == 401
            assert c.get("/api/projects").status_code == 401
            assert c.get("/api/tags").status_code == 401
            assert c.post("/api/tasks", json={"title": "x"}).status_code == 401
    finally:
        if saved is not None:
            app.dependency_overrides[require_user] = saved
