"""The "geolocation" field type (Datasources and Forms): a map-picked point
stored as "lat,lng" text — accepted when well-formed and in range, rejected
otherwise, on both master records and form submissions."""

import pytest

from app.core.form_validation import parse_geolocation


@pytest.mark.parametrize(
    ("raw", "expected"),
    [
        ("12.971599,77.594566", (12.971599, 77.594566)),
        ("-33.8688,151.2093", (-33.8688, 151.2093)),
        ("91,0", None),
        ("0,181", None),
        ("12.9", None),
        ("north,east", None),
        (12.9, None),
    ],
)
def test_parse_geolocation(raw, expected):
    assert parse_geolocation(raw) == expected


async def test_master_record_geolocation(client, auth_headers):
    master = await client.post(
        "/masters",
        headers=auth_headers,
        json={"name": "Sites", "field_schema": [{"name": "site", "type": "text"}, {"name": "location", "type": "geolocation"}]},
    )
    assert master.status_code == 201, master.text
    master_id = master.json()["id"]

    ok = await client.post(f"/masters/{master_id}/records", headers=auth_headers, json={"field_values": {"site": "HQ", "location": "12.971599,77.594566"}})
    assert ok.status_code == 201, ok.text
    assert ok.json()["field_values"]["location"] == "12.971599,77.594566"

    bad = await client.post(f"/masters/{master_id}/records", headers=auth_headers, json={"field_values": {"site": "Moon", "location": "123,456"}})
    assert bad.status_code == 422
    assert "location" in bad.text


async def test_form_submission_geolocation(client, auth_headers):
    form = (
        await client.post(
            "/forms",
            headers=auth_headers,
            json={"name": "Site visit", "field_definitions": [{"name": "where", "type": "geolocation", "label": "Where"}]},
        )
    ).json()
    body = {"form_id": form["form_id"], "form_version": form["version"]}

    bad = await client.post("/form-submissions", headers=auth_headers, json={**body, "field_values": {"where": "somewhere"}})
    assert bad.status_code == 422
    assert bad.json()["detail"][0]["msg"] == "Where: Must be a location picked on the map (latitude,longitude)."

    ok = await client.post("/form-submissions", headers=auth_headers, json={**body, "field_values": {"where": "-33.868800,151.209300"}})
    assert ok.status_code == 201, ok.text
