from fastapi.testclient import TestClient

from turbo_agent_auth.app import create_app
from turbo_agent_auth.config.runtime import reset_runtime_cache
from turbo_agent_auth.services.auth_service import _apply_runtime_defaults


def _make_client():
    return TestClient(create_app())


def test_runtime_callback_url_endpoint(monkeypatch):
    monkeypatch.delenv("AUTH_CALLBACK_URL", raising=False)
    monkeypatch.delenv("AUTH_CALLBACK_BASE_URL", raising=False)
    monkeypatch.delenv("AUTH_CALLBACK_PATH", raising=False)
    reset_runtime_cache()

    client = _make_client()
    resp = client.get("/v1/runtime/callback-url")
    assert resp.status_code == 200
    assert resp.json() == {"callbackUrl": None, "configured": False}

    monkeypatch.setenv("AUTH_CALLBACK_URL", "https://auth.example.com/callback")
    reset_runtime_cache()
    resp = client.get("/v1/runtime/callback-url")
    assert resp.status_code == 200
    assert resp.json() == {
        "callbackUrl": "https://auth.example.com/callback",
        "configured": True,
    }


def test_runtime_callback_with_base_and_path(monkeypatch):
    monkeypatch.setenv("AUTH_CALLBACK_BASE_URL", "https://auth.example.com")
    monkeypatch.setenv("AUTH_CALLBACK_PATH", "/custom/callback")
    monkeypatch.delenv("AUTH_CALLBACK_URL", raising=False)
    reset_runtime_cache()

    client = _make_client()
    resp = client.get("/v1/runtime/callback-url")
    assert resp.status_code == 200
    assert resp.json() == {
        "callbackUrl": "https://auth.example.com/custom/callback",
        "configured": True,
    }


def test_runtime_ip_allowlist_endpoint(monkeypatch):
    monkeypatch.delenv("AUTH_IP_ALLOWLIST", raising=False)
    monkeypatch.delenv("AUTH_WHITELIST_IPS", raising=False)
    reset_runtime_cache()

    client = _make_client()
    resp = client.get("/v1/runtime/ip-allowlist")
    assert resp.status_code == 200
    assert resp.json() == {"ipAllowList": [], "configured": False}

    monkeypatch.setenv("AUTH_IP_ALLOWLIST", "1.1.1.1, 2.2.2.2")
    reset_runtime_cache()
    resp = client.get("/v1/runtime/ip-allowlist")
    assert resp.status_code == 200
    assert resp.json() == {
        "ipAllowList": ["1.1.1.1", "2.2.2.2"],
        "configured": True,
    }


def test_apply_runtime_defaults_injects_callback(monkeypatch):
    monkeypatch.setenv("AUTH_CALLBACK_URL", "https://auth.local/cb")
    reset_runtime_cache()

    result = _apply_runtime_defaults({})
    assert result["callback_url"] == "https://auth.local/cb"
    assert result["redirect_uri"] == "https://auth.local/cb"

    monkeypatch.delenv("AUTH_CALLBACK_URL", raising=False)
    reset_runtime_cache()
    result_after_clear = _apply_runtime_defaults({})
    assert "callback_url" not in result_after_clear
    assert "redirect_uri" not in result_after_clear