#!/usr/bin/env bash
set -euo pipefail

# Manual end-to-end probe for GET /api/satellite/tiles/latlon strict validation
# (AZ-811). Each failure call should return HTTP 400 with an
# `application/problem+json` body. The happy path should return HTTP 200.
#
# Two enforcement layers:
#   1. RejectUnknownQueryParamsEndpointFilter — rejects any query key outside
#      {lat, lon, zoom}.
#   2. WithValidation<GetTileByLatLonQuery> — range-checks lat, lon, zoom.
#
# Usage:
#   API_URL=https://localhost:8080 JWT="<bearer-token>" ./scripts/probe_latlon_validation.sh

API_URL="${API_URL:-https://localhost:8080}"
JWT="${JWT:-}"
PATH_LATLON="${API_URL%/}/api/satellite/tiles/latlon"

if [[ -z "${JWT}" ]]; then
    echo "ERROR: set JWT env var to a bearer token. Mint one via:"
    echo "  dotnet run --project SatelliteProvider.IntegrationTests -- --mint-only"
    exit 2
fi

curl_args=(-sS -k -H "Authorization: Bearer ${JWT}" -X GET)

probe() {
    local label="$1"
    local query="$2"
    local expected_status="$3"

    echo "----- ${label} (expecting HTTP ${expected_status}) -----"
    local response
    response=$(curl "${curl_args[@]}" "${PATH_LATLON}?${query}" -w "\nHTTP_STATUS=%{http_code}\n")
    echo "${response}"
    local actual_status
    actual_status=$(echo "${response}" | tail -n 1 | sed 's/HTTP_STATUS=//')
    if [[ "${actual_status}" != "${expected_status}" ]]; then
        echo "FAIL: expected HTTP ${expected_status}, got ${actual_status}"
        return 1
    fi
    echo "OK: HTTP ${expected_status}"
    echo
}

probe "happy-path"             "lat=47.461747&lon=37.647063&zoom=18"     200
# Validator rules — NotNull (missing required) + InclusiveBetween (range)
probe "missing-lat"            "lon=37.647063&zoom=18"                   400
probe "missing-lon"            "lat=47.461747&zoom=18"                   400
probe "missing-zoom"           "lat=47.461747&lon=37.647063"             400
probe "lat-out-of-range"       "lat=91&lon=37.647063&zoom=18"            400
probe "lon-out-of-range"       "lat=47.461747&lon=181&zoom=18"           400
probe "zoom-out-of-range"      "lat=47.461747&lon=37.647063&zoom=30"     400
# Envelope rule: unknown query params (legacy pre-AZ-811 wire names + hostile probes)
probe "legacy-param-names"     "Latitude=47.461747&Longitude=37.647063&ZoomLevel=18" 400
probe "hostile-debug-admin"    "lat=47.461747&lon=37.647063&zoom=18&debug=1&admin=true" 400
probe "typo-zooom"             "lat=47.461747&lon=37.647063&zooom=18"    400
# Type mismatch (model binder)
probe "lat-type-mismatch"      "lat=fifty&lon=37.647063&zoom=18"         400

echo "All probes passed."
