"""Tests for the FastAPI integration."""

import pytest

from yoro.fastapi import create_app

pytest.importorskip("httpx")
from httpx import ASGITransport, AsyncClient


@pytest.fixture
def app():
    return create_app()


@pytest.fixture
async def client(app):
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        yield c


@pytest.mark.anyio
async def test_health(client):
    resp = await client.get("/health")
    assert resp.status_code == 200
    data = resp.json()
    assert data["status"] == "ok"


@pytest.mark.anyio
async def test_encode(client):
    resp = await client.get("/encode", params={"lat": 6.8, "lon": -5.3, "domain": "CI"})
    assert resp.status_code == 200
    data = resp.json()
    assert data["code"].startswith("CI-")
    assert "bounds" in data


@pytest.mark.anyio
async def test_decode(client):
    # First encode to get a valid code
    resp = await client.get("/encode", params={"lat": 6.8, "lon": -5.3})
    code = resp.json()["code"]

    resp = await client.get("/decode", params={"code": code})
    assert resp.status_code == 200
    data = resp.json()
    assert data["code"] == code
    assert "neighbors" in data


@pytest.mark.anyio
async def test_decode_invalid_format(client):
    resp = await client.get("/decode", params={"code": "NOPE"})
    assert resp.status_code == 400


@pytest.mark.anyio
async def test_precisions(client):
    resp = await client.get("/precisions", params={"domain": "CI"})
    assert resp.status_code == 200
    data = resp.json()
    assert data["domain"] == "CI"
    assert len(data["levels"]) > 0
    precisions = [lv["precision"] for lv in data["levels"]]
    assert 12 in precisions
    assert 19 in precisions


@pytest.mark.anyio
async def test_domains(client):
    resp = await client.get("/domains")
    assert resp.status_code == 200
    data = resp.json()
    assert "CI" in data["domains"]
    assert "XX" in data["domains"]
