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

root_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
work_dir=$(mktemp -d)
port=18082
base_url="http://127.0.0.1:${port}/dmn.php"

cleanup() {
  kill "${server_pid:-}" 2>/dev/null || true
  wait "${server_pid:-}" 2>/dev/null || true
  rm -rf "$work_dir"
}
trap cleanup EXIT

php -S "127.0.0.1:${port}" -t "$root_dir" >"$work_dir/server.log" 2>&1 &
server_pid=$!
for _ in {1..30}; do
  curl --silent --output /dev/null "$base_url" && break
  sleep 0.1
done

request() {
  local name=$1
  shift
  curl --silent --show-error --dump-header "$work_dir/$name.headers" --output "$work_dir/$name.body" "$@"
}

assert_status() {
  local name=$1 expected=$2
  grep -q "^HTTP/.* $expected" "$work_dir/$name.headers"
}

assert_body() {
  local name=$1 text=$2
  grep -Fq "$text" "$work_dir/$name.body"
}

# GET: simple, hyphenated, repeated, and URL-encoded values.
request get --get "$base_url" --data-urlencode 'merchant-id=M-42' --data-urlencode 'note=hello world' --data-urlencode 'items[]=one' --data-urlencode 'items[]=two'
assert_status get 200
assert_body get 'merchant-id'
assert_body get 'hello world'
assert_body get '&quot;one&quot;,&quot;two&quot;'

# POST application/x-www-form-urlencoded: PHP must populate the form parameters.
request urlencoded -X POST -H 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'customer=Jane Doe' --data-urlencode 'reference=A&B=1' "$base_url"
assert_status urlencoded 200
assert_body urlencoded 'customer'
assert_body urlencoded 'Jane Doe'
assert_body urlencoded 'A&amp;B=1'

# POST raw form: preserve a non-form-encoded body for logging and safe display.
request raw_form -X POST -H 'Content-Type: text/plain' --data-binary 'invoice=INV-42&status=paid' "$base_url"
assert_status raw_form 200
assert_body raw_form 'Raw request body'
assert_body raw_form 'invoice=INV-42&amp;status=paid'

# POST JSON: decode and display the parsed structured payload.
request json -X POST -H 'Content-Type: application/json' --data '{"event":"paid","amount":12.5,"approved":true}' "$base_url"
assert_status json 200
assert_body json 'JSON payload'
assert_body json '&quot;event&quot;:&quot;paid&quot;'

# OPTIONS advertises the endpoint methods and deliberately has no response body.
request options -X OPTIONS "$base_url"
assert_status options 204
grep -qi '^Allow: GET, POST, HEAD, OPTIONS' "$work_dir/options.headers"
test ! -s "$work_dir/options.body"

# HEAD must return headers without an entity body.
request head -X HEAD "$base_url"
assert_status head 200
test ! -s "$work_dir/head.body"

echo 'HTTP scenarios passed: GET, form POST, raw POST, JSON POST, OPTIONS, HEAD.'
