#!/usr/bin/env bash
set -euo pipefail

echo "[start-web] Starting web service..."
echo "[start-web] Bun: $(bun --version || true)"

cd /app

export BUN_INSTALL_CACHE_DIR="${BUN_INSTALL_CACHE_DIR:-/tmp/bun-cache}"
mkdir -p "$BUN_INSTALL_CACHE_DIR"

echo "[start-web] Using bun cache dir: $BUN_INSTALL_CACHE_DIR"
echo "[start-web] Using APP_DIR=$(pwd)"
echo "[start-web] NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL:-}"
echo "[start-web] NEXT_PUBLIC_CONVEX_URL=${NEXT_PUBLIC_CONVEX_URL:-}"
echo "[start-web] DATABASE_URL=${DATABASE_URL:+set}"

# Ensure system deps for native modules (best-effort, idempotent)
if command -v apt-get >/dev/null 2>&1; then
  if [ "${SKIP_APT_BOOTSTRAP:-false}" = "true" ]; then
    echo "[start-web] SKIP_APT_BOOTSTRAP=true; skipping apt bootstrap"
  else
    # Ensure curl/gnupg for NodeSource setup
    if ! command -v curl >/dev/null 2>&1; then
      apt-get update -y || true
      apt-get install -y --no-install-recommends curl ca-certificates gnupg || true
    fi

    install_node() {
      local current_node_major=""
      if command -v node >/dev/null 2>&1; then
        current_node_major=$(node -v | sed -E 's/^v([0-9]+).*/\1/')
        if [ -n "$current_node_major" ] && [ "$current_node_major" -ge 20 ]; then
          return 0
        fi
      fi

      echo "[start-web] installing Node.js 22.x via NodeSource"
      curl -fsSL https://deb.nodesource.com/setup_22.x | bash - || true
      apt-get update -y || true
      apt-get install -y --no-install-recommends nodejs || true
    }

    # Base toolchain for native modules
    apt-get update -y || true
    apt-get install -y --no-install-recommends build-essential python3 make pkg-config || true

    if ! command -v openssl >/dev/null 2>&1; then
      echo "[start-web] openssl not found; installing via apt-get (requires root)"
      apt-get update -y || true
      apt-get install -y --no-install-recommends openssl ca-certificates || true
    fi
    if ! command -v node >/dev/null 2>&1 && [ -x /usr/bin/nodejs ]; then
      ln -sf /usr/bin/nodejs /usr/bin/node || true
    fi
    install_node
  fi
else
  echo "[start-web] apt-get unavailable; skipping system deps install" >&2
fi

# Aguardar PostgreSQL estar pronto
wait_for_postgres() {
  local max_attempts=30
  local attempt=1

  echo "[start-web] Aguardando PostgreSQL..."

  while [ $attempt -le $max_attempts ]; do
    if node -e "
      const url = process.env.DATABASE_URL;
      if (!url) { console.error('DATABASE_URL not set'); process.exit(1); }
      fetch(url.replace(/^postgresql:/, 'http:').replace(/\/[^/]+$/, '/'), { method: 'HEAD', signal: AbortSignal.timeout(2000) })
        .then(() => process.exit(0))
        .catch(() => process.exit(1));
    " 2>/dev/null; then
      echo "[start-web] PostgreSQL pronto!"
      return 0
    fi

    # Fallback: tenta via psql se disponivel
    if command -v psql >/dev/null 2>&1; then
      if psql "$DATABASE_URL" -c "SELECT 1" >/dev/null 2>&1; then
        echo "[start-web] PostgreSQL pronto (via psql)!"
        return 0
      fi
    fi

    # Fallback simples: verifica se o host responde
    local pg_host=$(echo "$DATABASE_URL" | sed -E 's/.*@([^:\/]+).*/\1/')
    local pg_port=$(echo "$DATABASE_URL" | sed -E 's/.*:([0-9]+)\/.*/\1/')
    if timeout 2 bash -c "echo >/dev/tcp/$pg_host/$pg_port" 2>/dev/null; then
      echo "[start-web] PostgreSQL acessivel na porta $pg_port!"
      return 0
    fi

    echo "[start-web] Tentativa $attempt/$max_attempts - PostgreSQL nao disponivel"
    sleep 2
    attempt=$((attempt + 1))
  done

  echo "[start-web] AVISO: PostgreSQL nao confirmado apos $max_attempts tentativas, continuando mesmo assim..."
  return 0
}

# Verificar se DATABASE_URL esta definida
if [ -z "${DATABASE_URL:-}" ]; then
  echo "[start-web] ERRO: DATABASE_URL nao definida"
  exit 1
fi

# Aguardar PostgreSQL em producao
if [ "${NODE_ENV:-}" = "production" ]; then
  wait_for_postgres
fi

# Bun keeps its store in node_modules/.bun by default; ensure it exists and is writable
mkdir -p node_modules/.bun >/dev/null 2>&1 || true

# Prisma generate (idempotent) and apply DB migrations
echo "[start-web] prisma generate (bun runtime)"
bunx --bun prisma generate

echo "[start-web] prisma migrate deploy (bun runtime)"
bunx --bun prisma migrate deploy

# Seed Better Auth users safely (ensure-only by default)
if [ "${SKIP_AUTH_SEED:-false}" != "true" ]; then
  echo "[start-web] seeding Better Auth users (ensure-only)"
  bun run auth:seed || true
else
  echo "[start-web] skipping auth seed (SKIP_AUTH_SEED=true)"
fi

echo "[start-web] launching Next.js"
PORT=${PORT:-3000}
NODE_MAJOR=$(command -v node >/dev/null 2>&1 && node -v | sed -E 's/^v([0-9]+).*/\1/' || echo "")
if [ -z "$NODE_MAJOR" ] || [ "$NODE_MAJOR" -lt 20 ]; then
  echo "[start-web] Node.js 20+ not available; aborting"
  exit 1
fi
exec node node_modules/next/dist/bin/next start --port "$PORT"
