#!/usr/bin/env bash
# Run on server as root:
#   cd /root/modstagram-next && bash scripts/server-fix-502.sh
set -euo pipefail

APP_DIR="${APP_DIR:-/root/modstagram-next}"
cd "$APP_DIR"
echo ">>> modstagram-next deploy | $APP_DIR"

# Stop anything blocking ports
pm2 delete modstagram-next 2>/dev/null || true
fuser -k 3004/tcp 2>/dev/null || true
fuser -k 3001/tcp 2>/dev/null || true

# PM2 config — port 3004 (nginx upstream on this server)
cat > "$APP_DIR/ecosystem.config.cjs" << EOF
module.exports = {
  apps: [{
    name: "modstagram-next",
    cwd: "$APP_DIR",
    script: "$APP_DIR/node_modules/next/dist/bin/next",
    args: "start --port 3004 --hostname 0.0.0.0",
    instances: 1,
    exec_mode: "fork",
    autorestart: true,
    max_restarts: 20,
    min_uptime: 5000,
    max_memory_restart: "900M",
    env: {
      NODE_ENV: "production",
      PORT: "3004",
      HOSTNAME: "0.0.0.0",
      UPSTREAM_API_URL: "https://api.modstagram.com",
      NEXT_PUBLIC_SOCKET_URL: "https://api.modstagram.com",
      NEXT_PUBLIC_IMAGE_BASE_URL: "https://api.modstagram.com/storage",
      NEXT_PUBLIC_BASE_URL: "/api/v1",
      NEXT_PUBLIC_SITE_URL: "https://modstagram.com",
    },
  }],
};
EOF

# Production env
if [ ! -f .env.production ]; then
  cat > .env.production << 'ENVEOF'
PORT=3004
HOSTNAME=0.0.0.0
UPSTREAM_API_URL=https://api.modstagram.com
NEXT_PUBLIC_SOCKET_URL=https://api.modstagram.com
NEXT_PUBLIC_IMAGE_BASE_URL=https://api.modstagram.com/storage
NEXT_PUBLIC_BASE_URL=/api/v1
NEXT_PUBLIC_SITE_URL=https://modstagram.com
ENVEOF
fi

# Copy Google Client ID from .env.local if present
if [ -f .env.local ] && grep -q GOOGLE .env.local 2>/dev/null; then
  grep GOOGLE .env.local >> .env.production 2>/dev/null || true
fi

npm pkg set scripts.start="next start --port 3004 --hostname 0.0.0.0"

echo ">>> npm install (do NOT run npm ci — lock file on server may be old) ..."
npm install @react-oauth/google@^0.13.5 --save
npm install

echo ">>> npm run build ..."
if ! npm run build; then
  echo ""
  echo "!!! BUILD FAILED — site stays 502 until build succeeds."
  echo "    Send the error lines above to fix the code/deps."
  exit 1
fi

if [ ! -f .next/BUILD_ID ]; then
  echo "ERROR: .next/BUILD_ID missing after build"
  exit 1
fi

echo ">>> PM2 start ..."
pm2 start "$APP_DIR/ecosystem.config.cjs" --update-env
pm2 save

sleep 3
echo ""
echo ">>> PM2 status:"
pm2 list | grep -E "modstagram|name" || pm2 list

echo ""
echo ">>> Ports:"
ss -tlnp | grep -E '3001|3004' || echo "(nothing on 3001/3004)"

echo ""
HTTP=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:3004/ || echo "000")
echo ">>> curl 127.0.0.1:3004 → HTTP $HTTP"

if [ "$HTTP" != "200" ] && [ "$HTTP" != "304" ] && [ "$HTTP" != "307" ]; then
  echo ""
  echo "!!! Next.js not healthy. Last logs:"
  pm2 logs modstagram-next --lines 40 --nostream
  exit 1
fi

echo ""
echo ">>> OK — modstagram.com should work (nginx → 3004)."
