from __future__ import annotations

import pytest

from scripts.oidc_smoke import check_oidc


class _FakeResponse:
    def __init__(self, payload: dict, status_code: int = 200):
        self._payload = payload
        self.status_code = status_code

    def json(self) -> dict:
        return self._payload

    def raise_for_status(self) -> None:
        if self.status_code >= 400:
            raise RuntimeError(f"HTTP {self.status_code}")


class _FakeClient:
    def __init__(self, responses: list[_FakeResponse]):
        self.responses = responses
        self.calls: list[str] = []

    def get(self, url: str) -> _FakeResponse:
        self.calls.append(url)
        if not self.responses:
            raise AssertionError("No fake responses left")
        return self.responses.pop(0)


def test_oidc_smoke_skips_health_when_disabled() -> None:
    client = _FakeClient([_FakeResponse({"enabled": False, "provider_label": "Keycloak", "login_path": "/auth/oidc/start"})])

    summary = check_oidc("http://localhost:8080/", client=client)

    assert summary["config"]["enabled"] is False
    assert summary["health"] is None
    assert client.calls == ["http://localhost:8080/proxy/auth/auth/oidc/config"]


def test_oidc_smoke_can_require_enabled() -> None:
    client = _FakeClient([_FakeResponse({"enabled": False, "provider_label": "Keycloak", "login_path": "/auth/oidc/start"})])

    with pytest.raises(RuntimeError):
        check_oidc("http://localhost:8080", client=client, require_enabled=True)


def test_oidc_smoke_checks_health_when_enabled() -> None:
    client = _FakeClient(
        [
            _FakeResponse({"enabled": True, "provider_label": "Keycloak", "login_path": "/auth/oidc/start"}),
            _FakeResponse({"status": "ok", "provider": "keycloak", "jwks_loaded": True}),
        ]
    )

    summary = check_oidc("http://localhost:8080", client=client)

    assert summary["config"]["enabled"] is True
    assert summary["health"]["status"] == "ok"
    assert client.calls == [
        "http://localhost:8080/proxy/auth/auth/oidc/config",
        "http://localhost:8080/proxy/auth/auth/oidc/health",
    ]
