import json
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

from planemapper.provisioning.airspace import download


def test_download_no_api_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    airspace_path = tmp_path / "airspace.geojson"
    monkeypatch.delenv("OPENAIP_API_KEY", raising=False)
    with patch("planemapper.provisioning.airspace.AIRSPACE_PATH", airspace_path):
        download(51.5, -0.1, 100)
    data = json.loads(airspace_path.read_text())
    assert data["type"] == "FeatureCollection"
    assert data["features"] == []


def test_download_with_api_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    airspace_path = tmp_path / "airspace.geojson"
    monkeypatch.setenv("OPENAIP_API_KEY", "testkey123")
    mock_resp = MagicMock()
    mock_resp.ok = True
    mock_resp.text = '{"type":"FeatureCollection","features":[]}'
    with (
        patch("planemapper.provisioning.airspace.requests.get", return_value=mock_resp),
        patch("planemapper.provisioning.airspace.AIRSPACE_PATH", airspace_path),
    ):
        download(51.5, -0.1, 100)
    assert airspace_path.exists()
