"""Auth dependency — sprawdza że bez API_KEYS przepuszcza, a z API_KEYS wymaga klucza.

Endpointy /healthz i /readyz są poza auth (sprawdzane wprost), reszta przez dependency.
Testujemy bezpośrednio na funkcji `require_api_key`, niezależnie od DB.
"""
from __future__ import annotations

import pytest
from fastapi import HTTPException

from app.auth import require_api_key
from app.config import get_settings


def _reset_settings_cache() -> None:
    get_settings.cache_clear()


@pytest.fixture(autouse=True)
def _restore_env(monkeypatch: pytest.MonkeyPatch) -> None:
    # Każdy test startuje z czystą wartością API_KEYS i wyczyszczonym cache.
    # setenv("") nadpisuje też wartość z .env (delenv tylko usuwa z os.environ).
    monkeypatch.setenv("API_KEYS", "")
    _reset_settings_cache()
    yield
    _reset_settings_cache()


def test_disabled_when_api_keys_empty() -> None:
    # Z pustym API_KEYS auth jest disabled — przepuszcza nawet bez headera.
    require_api_key(x_api_key=None, authorization=None)


def test_accepts_x_api_key_header(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("API_KEYS", "alice-secret,bob-secret")
    _reset_settings_cache()
    require_api_key(x_api_key="alice-secret", authorization=None)


def test_accepts_bearer_authorization(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("API_KEYS", "alice-secret")
    _reset_settings_cache()
    require_api_key(x_api_key=None, authorization="Bearer alice-secret")


def test_rejects_unknown_key(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("API_KEYS", "alice-secret")
    _reset_settings_cache()
    with pytest.raises(HTTPException) as exc:
        require_api_key(x_api_key="hacker", authorization=None)
    assert exc.value.status_code == 401


def test_rejects_missing_when_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("API_KEYS", "alice-secret")
    _reset_settings_cache()
    with pytest.raises(HTTPException) as exc:
        require_api_key(x_api_key=None, authorization=None)
    assert exc.value.status_code == 401


def test_settings_parses_csv_keys_with_whitespace(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("API_KEYS", " alice , bob ,, charlie ")
    _reset_settings_cache()
    keys = get_settings().api_keys
    assert keys == {"alice", "bob", "charlie"}
