#!/bin/bash
set -e
PATH=/home/allaun/.nix-profile/bin:/usr/bin:/bin
export PGPASSWORD=postgres

echo "=== Creating SQLx migration table ==="
PGPASSWORD=postgres psql -h localhost -U postgres -d appflowy -f /tmp/fix_appflowy.sql 2>&1 || true

COUNT=$(PGPASSWORD=postgres psql -h localhost -U postgres -d appflowy -t -A -c 'SELECT COUNT(*) FROM auth._sqlx_migrations' 2>/dev/null)
echo "SQLx migrations tracked: $COUNT"

echo "=== Starting AppFloyo ==="
podman rm -f appflowy_cloud 2>/dev/null || true
podman run -d --name appflowy_cloud \
  --network host \
  -e APPFLOWY_DATABASE_URL="postgres://postgres:postgres@localhost:5432/appflowy?sslmode=disable&options=-c%20search_path=public" \
  -e APPFLOWY_ENVIRONMENT=production \
  -e APPFLOWY_REDIS_URI=redis://localhost:6379 \
  -e APPFLOWY_GOTRUE_JWT_SECRET=jwt_ \
  -e APPFLOWY_GOTRUE_JWT_EXP=3600 \
  -e APPFLOWY_GOTRUE_BASE_URL=http://localhost:9999 \
  -e APPFLOWY_BASE_URL=https://researchstack.info/appflowy \
  -e APPFLOWY_WEB_URL=https://researchstack.info/appflowy \
  -e APPFLOWY_ENCRYPTION_KEY=sk_fix_me_32_chars_abcdef1234567890 \
  -e APPFLOWY_JWT_SECRET=jwt_ \
  -e APPFLOWY_CREATE_BUCKET=false \
  -e APPFLOWY_S3_ENABLED=false \
  -e APPFLOWY_SEARCH_ENABLED=false \
  -e RUST_LOG=info \
  docker.io/appflowyinc/appflowy_cloud:latest

echo "=== Done. Checking health in 30s ==="
sleep 30
curl -s -o /dev/null -w "AppFloyo: %{http_code}\n" http://localhost:8000/api/health 2>/dev/null
