from __future__ import annotations

"""Tests for the tiny health and Monero endpoints."""

import json
from urllib.error import URLError

from atlas_portal.app_factory import create_app
from atlas_portal.routes import monero


def test_monero_endpoint_returns_upstream_json(monkeypatch) -> None:
    class DummyResponse:
        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc, tb):
            return False

        def read(self):
            return json.dumps({"status": "OK", "nettype": "mainnet"}).encode("utf-8")

    monkeypatch.setattr(monero, "urlopen", lambda *args, **kwargs: DummyResponse())

    app = create_app()
    client = app.test_client()

    resp = client.get("/api/monero/get_info")

    assert resp.status_code == 200
    assert resp.get_json()["status"] == "OK"


def test_monero_endpoint_handles_upstream_failure(monkeypatch) -> None:
    def boom(*args, **kwargs):
        raise URLError("boom")

    monkeypatch.setattr(monero, "urlopen", boom)

    app = create_app()
    client = app.test_client()

    resp = client.get("/api/monero/get_info")

    assert resp.status_code == 503
    assert resp.get_json()["url"].startswith("http://")
