#!/usr/bin/env bash

set -euo pipefail

API_BASE_URL="${API_BASE_URL:-}"
ACCESS_TOKEN="${ACCESS_TOKEN:-}"
VARIANT_ID="${VARIANT_ID:-}"
BASE_URL="${BASE_URL:-}"

if [[ -z "${API_BASE_URL}" ]]; then
  echo "Missing API_BASE_URL"
  exit 1
fi

if [[ -z "${ACCESS_TOKEN}" ]]; then
  echo "Missing ACCESS_TOKEN"
  exit 1
fi

if [[ -z "${VARIANT_ID}" ]]; then
  echo "Missing VARIANT_ID"
  exit 1
fi

if [[ -z "${BASE_URL}" ]]; then
  echo "Missing BASE_URL"
  exit 1
fi

AUTH_HEADER="Authorization: Bearer ${ACCESS_TOKEN}"
CONTENT_HEADER="Content-Type: application/json"

echo ""
echo "== Create Editor Session =="
curl --silent --show-error --fail \
  -X POST \
  -H "${AUTH_HEADER}" \
  -H "${CONTENT_HEADER}" \
  -d "{
    \"variant_id\": \"${VARIANT_ID}\",
    \"base_url\": \"${BASE_URL}\",
    \"mode\": \"edit\"
  }" \
  "${API_BASE_URL}/api/editor/sessions"

echo ""
echo ""
echo "== Load Variant Changes =="
curl --silent --show-error --fail \
  -H "${AUTH_HEADER}" \
  "${API_BASE_URL}/api/editor/variants/${VARIANT_ID}/changes"

echo ""
echo ""
echo "== Save Variant Changes =="
curl --silent --show-error --fail \
  -X PUT \
  -H "${AUTH_HEADER}" \
  -H "${CONTENT_HEADER}" \
  -d "{
    \"items\": [
      {
        \"change_type\": \"replace_text\",
        \"selector_type\": \"css\",
        \"selector_value\": \"h1\",
        \"sort_order\": 0,
        \"enabled\": true,
        \"payload\": {
          \"text\": \"Smoke Test Heading\"
        }
      }
    ]
  }" \
  "${API_BASE_URL}/api/editor/variants/${VARIANT_ID}/changes"

echo ""
echo ""
echo "== Build Preview =="
curl --silent --show-error --fail \
  -X POST \
  -H "${AUTH_HEADER}" \
  -H "${CONTENT_HEADER}" \
  -d "{
    \"variant_id\": \"${VARIANT_ID}\",
    \"items\": [
      {
        \"change_type\": \"replace_text\",
        \"selector_type\": \"css\",
        \"selector_value\": \"h1\",
        \"sort_order\": 0,
        \"enabled\": true,
        \"payload\": {
          \"text\": \"Smoke Test Heading\"
        }
      }
    ]
  }" \
  "${API_BASE_URL}/api/editor/previews/build"

echo ""
echo ""
echo "Editor smoke test completed."
