#!/usr/bin/env bash
# 08_gateway_contracts.sh — GOLAKE-003.
# Gateway proxies /v1/* to the right upstream and preserves the
# upstream's status code. Compares gateway's response against the
# direct-port response for each route.

set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/../lib/env.sh"
source "${SCRIPT_DIR}/../lib/http.sh"
source "${SCRIPT_DIR}/../lib/assert.sh"

CASE_ID="GOLAKE-003"
CASE_NAME="Gateway proxy — route + status passthrough"
CASE_TYPE="contract"
if [ "${1:-}" = "--metadata-only" ]; then return 0 2>/dev/null || exit 0; fi

# Each row: <probe-name> <gateway-path> <upstream-url-path>.
# Verifies that gateway and direct-upstream return the same status.
ROUTES=(
    "storage_list:/v1/storage/list:${PROOF_STORAGED_URL}/storage/list"
    "catalog_list:/v1/catalog/list:${PROOF_CATALOGD_URL}/catalog/list"
)

for spec in "${ROUTES[@]}"; do
    IFS=':' read -r name gw_path up_url <<< "$spec"

    proof_get "$CASE_ID" "${name}_gw"   "${PROOF_GATEWAY_URL}${gw_path}" >/dev/null
    proof_get "$CASE_ID" "${name}_up"   "${up_url}"                       >/dev/null

    gw_status=$(proof_status_of "$CASE_ID" "${name}_gw")
    up_status=$(proof_status_of "$CASE_ID" "${name}_up")

    # Status passthrough — gateway must return what the upstream returned.
    proof_assert_eq "$CASE_ID" "${name}: gateway status matches upstream" \
        "$up_status" "$gw_status"

    # Body shape preserved — sha256 must match (gateway is a proxy, not a transformer).
    gw_body_sha=$(sha256sum \
        "${PROOF_REPORT_DIR}/raw/http/${CASE_ID}/${name}_gw.body" | awk '{print $1}')
    up_body_sha=$(sha256sum \
        "${PROOF_REPORT_DIR}/raw/http/${CASE_ID}/${name}_up.body" | awk '{print $1}')
    proof_assert_eq "$CASE_ID" "${name}: gateway body sha matches upstream" \
        "$up_body_sha" "$gw_body_sha"
done

# Status-passthrough on a 4xx — POST /v1/sql with empty body must
# return the same 4xx as the direct port.
proof_post "$CASE_ID" "sql_empty_gw" "${PROOF_GATEWAY_URL}/v1/sql" \
    "application/json" '{"sql":""}' >/dev/null
proof_post "$CASE_ID" "sql_empty_up" "${PROOF_QUERYD_URL}/sql" \
    "application/json" '{"sql":""}' >/dev/null

gw_status=$(proof_status_of "$CASE_ID" "sql_empty_gw")
up_status=$(proof_status_of "$CASE_ID" "sql_empty_up")
proof_assert_eq "$CASE_ID" "sql empty: gateway status matches upstream" \
    "$up_status" "$gw_status"
proof_assert_eq "$CASE_ID" "sql empty: status is 4xx (400)" "400" "$gw_status"
