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

echo "[start-web] Starting web service..."
echo "[start-web] Node: $(node -v || true)"

cd /app

# Ensure pnpm available in this base image
ensure_pnpm() {
  if command -v pnpm >/dev/null 2>&1; then
    return 0
  fi

  local runtime_home="${HOME:-}"
  if [ -z "$runtime_home" ] || [ ! -d "$runtime_home" ] || [ ! -w "$runtime_home" ]; then
    runtime_home="$(getent passwd "$(id -u)" | cut -d: -f6 2>/dev/null || true)"
  fi
  if [ -z "$runtime_home" ] || [ ! -d "$runtime_home" ] || [ ! -w "$runtime_home" ]; then
    runtime_home="/tmp"
  fi

  local local_bin="${runtime_home}/.local/bin"
  local pnpm_prefix="${runtime_home}/.local/share/pnpm"
  local corepack_home="${runtime_home}/.local/share/corepack"

  export PATH="${local_bin}:$PATH"
  export COREPACK_HOME="${corepack_home}"

  mkdir -p "$local_bin" "$pnpm_prefix" "$corepack_home" >/dev/null 2>&1 || true

  if command -v pnpm >/dev/null 2>&1; then
    return 0
  fi

  if command -v corepack >/dev/null 2>&1; then
    corepack prepare pnpm@9 --activate >/dev/null 2>&1 || true
    corepack enable --install-directory "$local_bin" pnpm >/dev/null 2>&1 || true
  fi

  if command -v pnpm >/dev/null 2>&1; then
    return 0
  fi

  if command -v npm >/dev/null 2>&1; then
    npm install --prefix "$pnpm_prefix" pnpm@9 >/dev/null 2>&1 || true
    if [ -x "${pnpm_prefix}/node_modules/.bin/pnpm" ]; then
      ln -sf "${pnpm_prefix}/node_modules/.bin/pnpm" "${local_bin}/pnpm" >/dev/null 2>&1 || true
    fi
  fi

  if command -v pnpm >/dev/null 2>&1; then
    return 0
  fi

  echo "[start-web] pnpm not available; aborting startup" >&2
  exit 1
}

ensure_pnpm

echo "[start-web] pnpm version: $(pnpm -v 2>/dev/null || echo 'unavailable')"
echo "[start-web] pnpm path: $(command -v pnpm || echo 'not found')"

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] PNPM_STORE_DIR=${PNPM_STORE_DIR:-/tmp/pnpm-store}"

# Ensure pnpm uses container-local store (not host bind mount)
pnpm config set store-dir "${PNPM_STORE_DIR:-/tmp/pnpm-store}" >/dev/null 2>&1 || true

# Prisma generate (idempotent) and apply DB migrations
echo "[start-web] prisma generate"
pnpm prisma:generate

echo "[start-web] prisma migrate deploy"
pnpm exec prisma migrate deploy

# Seed Better Auth users safely (ensure-only by default)
echo "[start-web] seeding Better Auth users (ensure-only)"
pnpm auth:seed || true

echo "[start-web] launching Next.js"
exec pnpm start -p 3000
