#!/bin/bash
set -euo pipefail

export SUPABASE_ANON_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0"

echo "[chatdesk-ui] Waiting for Kong to proxy PostgREST..."

until curl -s -o /dev/null -w "%{http_code}" -H "apikey: $SUPABASE_ANON_KEY" http://localhost:8000/rest/v1/ | grep -qE "^(200|401|403)$"; do
  echo "[chatdesk-ui] Still waiting for /rest/v1/ ..."
  sleep 3
done


# ✅ 设置 SUPABASE_URL，如果为空则使用默认值
if [ -z "${SUPABASE_URL:-}" ]; then
  SUPABASE_URL="http://localhost:8000"
fi

# ✅ 删除旧的 env.js（如果存在）
ENV_FILE="/supabase/chatdesk/public/env.js"
if [ -f "$ENV_FILE" ]; then
  echo "[chatdesk-ui] Removing old env.js"
  rm -f "$ENV_FILE"
fi

# ✅ 写入新的 env.js
echo "[chatdesk-ui] Writing env.js with SUPABASE_URL=$SUPABASE_URL"
cat <<EOF > "$ENV_FILE"
window.RUNTIME_ENV = {
  "SUPABASE_URL": "${SUPABASE_URL}"
};
EOF


echo "[chatdesk-ui] API is reachable via Kong. Starting UI..."

/bin/bash /supabase/chatdesk/init.sh

cd /supabase/chatdesk
exec npm run start
