#!/usr/bin/env bash

set -euo pipefail

BASE_URL="https://explorer.d-bis.org"
INTERNAL_SECRET="${ACCESS_INTERNAL_SECRET:-}"
API_KEY="${ACCESS_TEST_API_KEY:-}"
METHOD_NAME="eth_chainId"
REQUEST_COUNT="1"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --base-url)
            BASE_URL="$2"
            shift 2
            ;;
        --internal-secret)
            INTERNAL_SECRET="$2"
            shift 2
            ;;
        --api-key)
            API_KEY="$2"
            shift 2
            ;;
        --method)
            METHOD_NAME="$2"
            shift 2
            ;;
        --request-count)
            REQUEST_COUNT="$2"
            shift 2
            ;;
        *)
            echo "Unknown argument: $1" >&2
            exit 1
            ;;
    esac
done

VALIDATE_URL="${BASE_URL%/}/explorer-api/v1/access/internal/validate-key"

echo "== Explorer access edge-hook verification =="
echo "Validator: $VALIDATE_URL"

if [[ -z "$INTERNAL_SECRET" ]]; then
    echo "ERROR: internal secret is required. Set ACCESS_INTERNAL_SECRET or pass --internal-secret." >&2
    exit 1
fi

headers_file="$(mktemp)"
body_file="$(mktemp)"
trap 'rm -f "$headers_file" "$body_file"' EXIT

curl_args=(
    -sS
    -D "$headers_file"
    -o "$body_file"
    -w "%{http_code}"
    -X GET
    -H "X-Access-Internal-Secret: $INTERNAL_SECRET"
    -H "X-Access-Method: $METHOD_NAME"
    -H "X-Access-Request-Count: $REQUEST_COUNT"
)

if [[ -n "$API_KEY" ]]; then
    curl_args+=(-H "X-API-Key: $API_KEY")
fi

status="$(curl "${curl_args[@]}" "$VALIDATE_URL")"

echo "HTTP status: $status"

if [[ "$status" == "200" ]]; then
    echo "Validation accepted."
    echo "Returned headers:"
    grep -Ei '^(x-validated-|x-quota-remaining:)' "$headers_file" || true
    exit 0
fi

echo "Validation rejected."
if [[ -s "$body_file" ]]; then
    echo "Response body:"
    cat "$body_file"
fi
exit 1
