#!/usr/bin/env bash

set -euo pipefail

BATCH="${1:-all}"
ENV_FILE="${2:-}"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

load_env_file() {
  local env_file="$1"

  if [[ -z "${env_file}" ]]; then
    return 0
  fi

  if [[ ! -f "${env_file}" ]]; then
    echo "Env file not found: ${env_file}"
    exit 1
  fi

  set -a
  # shellcheck disable=SC1090
  source "${env_file}"
  set +a
}

check_required_vars() {
  local batch_name="$1"
  shift
  local missing=()
  local var_name value

  for var_name in "$@"; do
    value="${!var_name:-}"
    if [[ -z "${value}" ]]; then
      missing+=("${var_name}")
    fi
  done

  if (( ${#missing[@]} > 0 )); then
    echo ""
    echo "Missing required env for ${batch_name}:"
    printf '  - %s\n' "${missing[@]}"
    echo ""
    echo "Tip:"
    echo "  Copy scripts/.env.validation.example and fill the required values."
    exit 1
  fi
}

run_validation_smoke() {
  check_required_vars "validation smoke" API_BASE_URL ACCESS_TOKEN
  echo ""
  echo ">>> Batch 1 / Batch 2: validation_smoke_test.sh"
  bash "${ROOT_DIR}/scripts/validation_smoke_test.sh"
}

run_editor_smoke() {
  check_required_vars "editor smoke" API_BASE_URL ACCESS_TOKEN VARIANT_ID BASE_URL
  echo ""
  echo ">>> Batch 3: editor_smoke_test.sh"
  bash "${ROOT_DIR}/scripts/editor_smoke_test.sh"
}

run_runtime_smoke() {
  check_required_vars \
    "runtime smoke" \
    API_BASE_URL \
    PAGE_URL \
    EXPERIMENT_ID \
    EXPERIMENT_KEY \
    VARIANT_ID \
    VARIANT_KEY

  if [[ -z "${SITE_ID:-}" && -z "${SITE_KEY:-}" ]]; then
    echo ""
    echo "Missing required env for runtime smoke:"
    echo "  - SITE_ID or SITE_KEY"
    echo ""
    echo "Tip:"
    echo "  Provide at least one of SITE_ID / SITE_KEY in your validation env."
    exit 1
  fi

  echo ""
  echo ">>> Batch 4: runtime_smoke_test.sh"
  bash "${ROOT_DIR}/scripts/runtime_smoke_test.sh"
}

print_usage() {
  cat <<'EOF'
Usage:
  bash scripts/run_validation_batch.sh <batch> [env-file]

Available batch values:
  batch1   Run health/auth smoke
  batch2   Run admin data smoke
  batch3   Run editor smoke
  batch4   Run runtime smoke
  batch1-3 Run batch1 + batch2 + batch3
  all      Run batch1 + batch2 + batch3 + batch4

Recommended:
  1. copy scripts/.env.validation.example to your own env file
  2. fill real staging values
  3. run batch1-3 first
  4. pass the env file path as the second argument
EOF
}

load_env_file "${ENV_FILE}"

case "${BATCH}" in
  batch1)
    run_validation_smoke
    ;;
  batch2)
    run_validation_smoke
    ;;
  batch3)
    run_editor_smoke
    ;;
  batch4)
    run_runtime_smoke
    ;;
  batch1-3)
    run_validation_smoke
    run_editor_smoke
    ;;
  all)
    run_validation_smoke
    run_editor_smoke
    run_runtime_smoke
    ;;
  help|-h|--help)
    print_usage
    exit 0
    ;;
  *)
    echo "Unknown batch: ${BATCH}"
    echo ""
    print_usage
    exit 1
    ;;
esac

echo ""
echo "Validation batch '${BATCH}' completed."
