#!/bin/sh
set -e

# Handle VITE_API_URL specially to preserve empty values
# If VITE_API_URL is unset, use default; if empty, preserve empty; otherwise use value
if [ -z "${VITE_API_URL+x}" ]; then
  export VITE_API_URL="/api"
elif [ -z "$VITE_API_URL" ]; then
  # If VITE_API_URL is explicitly set to empty string, use relative API path
  export VITE_API_URL="/api"
fi

# Default values for environment variables
export VITE_APP_TITLE=${VITE_APP_TITLE:-"BakeWise"}
export VITE_APP_VERSION=${VITE_APP_VERSION:-"1.0.0"}

# Default values for pilot program configuration
export VITE_PILOT_MODE_ENABLED=${VITE_PILOT_MODE_ENABLED:-"false"}
export VITE_PILOT_COUPON_CODE=${VITE_PILOT_COUPON_CODE:-"PILOT2025"}
export VITE_PILOT_TRIAL_MONTHS=${VITE_PILOT_TRIAL_MONTHS:-"3"}
export VITE_STRIPE_PUBLISHABLE_KEY=${VITE_STRIPE_PUBLISHABLE_KEY:-"pk_test_"}

# Create a runtime configuration file that can be loaded by the frontend
cat > /usr/share/nginx/html/runtime-config.js << EOL
window.__RUNTIME_CONFIG__ = {
  VITE_API_URL: '${VITE_API_URL}',
  VITE_APP_TITLE: '${VITE_APP_TITLE}',
  VITE_APP_VERSION: '${VITE_APP_VERSION}',
  VITE_PILOT_MODE_ENABLED: '${VITE_PILOT_MODE_ENABLED}',
  VITE_PILOT_COUPON_CODE: '${VITE_PILOT_COUPON_CODE}',
  VITE_PILOT_TRIAL_MONTHS: '${VITE_PILOT_TRIAL_MONTHS}',
  VITE_STRIPE_PUBLISHABLE_KEY: '${VITE_STRIPE_PUBLISHABLE_KEY}'
};
EOL

echo "Runtime configuration created:"
echo "  API URL: ${VITE_API_URL}"
echo "  Pilot Mode: ${VITE_PILOT_MODE_ENABLED}"
echo "  Pilot Coupon: ${VITE_PILOT_COUPON_CODE}"
echo "  Trial Months: ${VITE_PILOT_TRIAL_MONTHS}"
