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

BASE_URL="${BASE_URL:-http://dahlias.local}"
SKIP_CONTACT="${SKIP_CONTACT:-0}"

if ! command -v curl >/dev/null 2>&1; then
  echo "curl is required" >&2
  exit 1
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

request() {
  local method="$1"
  local url="$2"
  local data_file="${3:-}"
  local body_file="$TMP_DIR/body"
  local status

  if [[ -n "$data_file" ]]; then
    status=$(curl -sS -X "$method" -H "Content-Type: application/json" -o "$body_file" -w "%{http_code}" "$url" --data-binary "@$data_file")
  else
    status=$(curl -sS -X "$method" -o "$body_file" -w "%{http_code}" "$url")
  fi

  echo "$status"
}

json_get_first_id() {
  local key="$1"
  python3 -c 'import json, sys
key = sys.argv[1]
try:
    data = json.load(sys.stdin)
except Exception:
    print("")
    sys.exit(0)
items = data.get("data")
if isinstance(items, list) and items:
    first = items[0]
    if isinstance(first, dict):
        value = first.get(key)
        if value is not None:
            print(value)
' "$key"
}

expect_status() {
  local status="$1"
  local expected="$2"
  local label="$3"
  if [[ "$status" != "$expected" ]]; then
    echo "FAIL: $label (expected $expected, got $status)" >&2
    exit 1
  fi
  echo "OK: $label"
}

# Artists list
status=$(request GET "$BASE_URL/api.php?resource=artists&action=list")
body=$(cat "$TMP_DIR/body")
expect_status "$status" "200" "artists list"
artist_id=$(echo "$body" | json_get_first_id "id_artist")

# Artist detail (if id exists)
if [[ -n "$artist_id" ]]; then
  status=$(request GET "$BASE_URL/api.php?resource=artists&action=detail&id=$artist_id")
  body=$(cat "$TMP_DIR/body")
  expect_status "$status" "200" "artist detail"
else
  echo "SKIP: artist detail (no artist id found)"
fi

# Events list
status=$(request GET "$BASE_URL/api.php?resource=events&action=list")
body=$(cat "$TMP_DIR/body")
expect_status "$status" "200" "events list"
event_id=$(echo "$body" | json_get_first_id "id_event")

# Event detail (if id exists)
if [[ -n "$event_id" ]]; then
  status=$(request GET "$BASE_URL/api.php?resource=events&action=detail&id=$event_id")
  body=$(cat "$TMP_DIR/body")
  expect_status "$status" "200" "event detail"
else
  echo "SKIP: event detail (no event id found)"
fi

# Contact submit
if [[ "$SKIP_CONTACT" == "1" ]]; then
  echo "SKIP: contact submit"
else
  payload="$TMP_DIR/contact.json"
  cat > "$payload" <<JSON
{
  "name": "Smoke Test",
  "email": "smoke-test@example.test",
  "subject": "Smoke test",
  "content": "This is a test message from api-smoke-tests.sh"
}
JSON
  status=$(request POST "$BASE_URL/api.php?resource=contact&action=submit" "$payload")
  body=$(cat "$TMP_DIR/body")
  if [[ "$status" != "200" ]]; then
    echo "FAIL: contact submit (expected 200, got $status)" >&2
    echo "$body" >&2
    exit 1
  fi
  if ! echo "$body" | python3 -c 'import json, sys
try:
    data = json.load(sys.stdin)
    ok = data.get("status") == "success"
except Exception:
    ok = False
if not ok:
    sys.exit(1)
' 
  then
    echo "FAIL: contact submit (status not success)" >&2
    echo "$body" >&2
    exit 1
  fi
  echo "OK: contact submit"
fi

echo "All smoke tests passed."
