#!/usr/bin/env bash

set -euo pipefail

API_BASE_URL="${API_BASE_URL:-}"
ACCESS_TOKEN="${ACCESS_TOKEN:-}"
EXPERIMENT_ID="${EXPERIMENT_ID:-}"

if [[ -z "${API_BASE_URL}" ]]; then
  echo "Missing API_BASE_URL"
  echo "Example: API_BASE_URL=https://mktapi.ose.tw"
  exit 1
fi

if [[ -z "${ACCESS_TOKEN}" ]]; then
  echo "Missing ACCESS_TOKEN"
  echo "Example: ACCESS_TOKEN=<mkt_access_token>"
  exit 1
fi

AUTH_HEADER="Authorization: Bearer ${ACCESS_TOKEN}"

echo ""
echo "== Health =="
curl --silent --show-error --fail \
  "${API_BASE_URL}/health"

echo ""
echo ""
echo "== Readiness =="
curl --silent --show-error --fail \
  "${API_BASE_URL}/health/ready"

echo ""
echo ""
echo "== Auth / Me =="
curl --silent --show-error --fail \
  -H "${AUTH_HEADER}" \
  "${API_BASE_URL}/api/auth/me"

echo ""
echo ""
echo "== Experiments =="
curl --silent --show-error --fail \
  -H "${AUTH_HEADER}" \
  "${API_BASE_URL}/api/admin/experiments"

if [[ -n "${EXPERIMENT_ID}" ]]; then
  echo ""
  echo ""
  echo "== Experiment Detail =="
  curl --silent --show-error --fail \
    -H "${AUTH_HEADER}" \
    "${API_BASE_URL}/api/admin/experiments/${EXPERIMENT_ID}"

  echo ""
  echo ""
  echo "== Variants By Experiment =="
  curl --silent --show-error --fail \
    -H "${AUTH_HEADER}" \
    "${API_BASE_URL}/api/admin/variants?experiment_id=${EXPERIMENT_ID}"

  echo ""
  echo ""
  echo "== Releases By Experiment =="
  curl --silent --show-error --fail \
    -H "${AUTH_HEADER}" \
    "${API_BASE_URL}/api/admin/releases?experiment_id=${EXPERIMENT_ID}"
fi

echo ""
echo ""
echo "Smoke test completed."
