"""API key authentication."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from ocr_sprint.config import get_settings
from ocr_sprint.main import create_app


def _client_with_keys(monkeypatch: pytest.MonkeyPatch, keys: str) -> TestClient:
    monkeypatch.setenv("API_KEYS", keys)
    get_settings.cache_clear()
    return TestClient(create_app())


def test_auth_disabled_when_keys_empty(monkeypatch: pytest.MonkeyPatch) -> None:
    client = _client_with_keys(monkeypatch, "")
    response = client.get("/api/v1/documents/00000000-0000-0000-0000-000000000000")
    # 404 not 401: auth disabled, the endpoint just doesn't find the row.
    assert response.status_code == 404


def test_auth_rejects_missing_key(monkeypatch: pytest.MonkeyPatch) -> None:
    client = _client_with_keys(monkeypatch, "secret-1,secret-2")
    response = client.get("/api/v1/documents/00000000-0000-0000-0000-000000000000")
    assert response.status_code == 401


def test_auth_accepts_valid_key(monkeypatch: pytest.MonkeyPatch) -> None:
    client = _client_with_keys(monkeypatch, "secret-1,secret-2")
    response = client.get(
        "/api/v1/documents/00000000-0000-0000-0000-000000000000",
        headers={"X-API-Key": "secret-2"},
    )
    assert response.status_code == 404


def test_health_is_unprotected(monkeypatch: pytest.MonkeyPatch) -> None:
    client = _client_with_keys(monkeypatch, "secret-1")
    response = client.get("/api/v1/health")
    assert response.status_code == 200
