from __future__ import annotations

from types import SimpleNamespace

import pytest

from api import auth as auth_mod


class _DummyResp:
    def __init__(self, payload=None, status_code=200):
        self._payload = payload or {"keys": [{"kid": "k1"}]}
        self.status_code = status_code

    def raise_for_status(self):
        if self.status_code >= 400:
            raise RuntimeError("http error")

    def json(self):
        return self._payload


def test_jwks_cache_fetch_without_context_manager(monkeypatch):
    calls = []

    def _fake_get(self_or_url, url=None, **kwargs):
        # Handle both Session.get(url, ...) and requests.get(url, ...)
        actual_url = url if url is not None else self_or_url
        calls.append(actual_url)
        return _DummyResp({"keys": [{"kid": "kid-1"}]})

    cache = auth_mod.JWKSCache(ttl_seconds=60)
    monkeypatch.setattr("requests.Session.get", _fake_get)

    jwks = cache.get_jwks("https://issuer.example.com")
    assert jwks["keys"][0]["kid"] == "kid-1"
    assert calls


def test_verify_authorization_requires_explicit_dev_token(monkeypatch):
    monkeypatch.setenv("HIKAFLOW_DEV_AUTH", "true")
    monkeypatch.delenv("HIKAFLOW_DEV_TOKEN", raising=False)

    with pytest.raises(ValueError, match="HIKAFLOW_DEV_TOKEN must be set"):
        auth_mod.verify_authorization("Bearer abc", request=SimpleNamespace(client=SimpleNamespace(host="127.0.0.1")))


def test_validate_issuer_normalizes_before_allowlist(monkeypatch):
    monkeypatch.setenv("CLERK_ALLOWED_ISSUERS", "https://issuer.example.com")
    monkeypatch.delenv("CLERK_ALLOWED_HOSTS", raising=False)

    assert auth_mod._validate_issuer("https://issuer.example.com/") == "https://issuer.example.com"
