#!/usr/bin/env bash
# mobile-up-auth.sh — start the Expo mobile app with full Zitadel auth.
#
# Requires the backend to also be running in auth mode:
#   ./dev-up-auth.sh
#
# Requires src/mobile/.env (or env vars) to have:
#   EXPO_PUBLIC_ZITADEL_CLIENT_ID=<mobile client id from seed-branding.sh>
#
# Real device: replace localhost with your LAN IP in EXPO_PUBLIC_API_BASE_URL
# e.g.: EXPO_PUBLIC_API_BASE_URL=http://192.168.1.x:8000 ./mobile-up-auth.sh

set -euo pipefail
cd "$(dirname "$0")/src/mobile"

# Install dependencies if node_modules is missing or package.json is newer
if [ ! -d node_modules ] || [ package.json -nt node_modules ]; then
  echo "  Installing dependencies…"
  npm install
fi

# Load .env so we can validate required vars
if [ -f .env ]; then
  set -a; source .env; set +a
fi

export EXPO_PUBLIC_AUTH_BYPASS=false
export EXPO_PUBLIC_API_BASE_URL="${EXPO_PUBLIC_API_BASE_URL:-http://localhost:8000}"
export EXPO_PUBLIC_APP_URL="${EXPO_PUBLIC_APP_URL:-http://localhost:5173}"
export EXPO_PUBLIC_ZITADEL_ISSUER="${EXPO_PUBLIC_ZITADEL_ISSUER:-http://localhost:8080}"

if [ -z "${EXPO_PUBLIC_ZITADEL_CLIENT_ID:-}" ]; then
  echo ""
  echo "  Error: EXPO_PUBLIC_ZITADEL_CLIENT_ID is not set in src/mobile/.env"
  echo "  Get it from the Zitadel console (use the MOBILE/Native client, not the Web one):"
  echo "    http://localhost:8080  →  Projects → continuum → Applications → Continuum Mobile"
  echo ""
  exit 1
fi

echo ""
echo "  Continuum Mobile — full auth mode"
echo "  API      ${EXPO_PUBLIC_API_BASE_URL}"
echo "  Zitadel  ${EXPO_PUBLIC_ZITADEL_ISSUER}"
echo "  Auth     ON — OIDC Native (client: ${EXPO_PUBLIC_ZITADEL_CLIENT_ID})"
echo "  Press i → iOS simulator  |  a → Android emulator  |  s → Expo Go"
echo ""

npx expo start "$@"
