"""
Tests HTTP d'integration contre l'API Docker.
"""

import os

import pytest
import httpx


API_BASE = os.getenv("PW_API_BASE", "http://localhost:8001")
API_TOKEN = os.getenv("PW_API_TOKEN", "change_me")


def _client() -> httpx.Client:
    return httpx.Client(base_url=API_BASE, timeout=2.0)


def _is_api_up() -> bool:
    try:
        with _client() as client:
            resp = client.get("/health")
        return resp.status_code == 200
    except Exception:
        return False


@pytest.mark.skipif(not _is_api_up(), reason="API Docker indisponible")
def test_health_endpoint():
    """/health repond avec db/redis."""
    with _client() as client:
        resp = client.get("/health")
    assert resp.status_code == 200
    payload = resp.json()
    assert "db" in payload and "redis" in payload


@pytest.mark.skipif(not _is_api_up(), reason="API Docker indisponible")
def test_products_requires_token():
    """/products demande un token valide."""
    with _client() as client:
        resp = client.get("/products")
        assert resp.status_code == 401

        resp = client.get("/products", headers={"Authorization": f"Bearer {API_TOKEN}"})
        assert resp.status_code == 200
        assert isinstance(resp.json(), list)
