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

# First-time VPS setup for rebours
# Run: bash deploy/setup.sh

VPS="ordinarthur@10.10.0.13"
APP_DIR="/var/www/html/rebours"

echo "🔧 Setting up rebours on $VPS..."

# 1. Sync project files
rsync -avz --delete \
  --exclude node_modules \
  --exclude .env \
  --exclude dist \
  --exclude .git \
  ./ "$VPS:$APP_DIR/"

# 2. Setup on server
ssh "$VPS" << 'REMOTE'
  set -euo pipefail

  # Node.js 22 + pnpm (skip if already installed)
  if ! command -v node &>/dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
    sudo apt-get install -y nodejs
  fi
  if ! command -v pnpm &>/dev/null; then
    sudo corepack enable
    sudo corepack prepare pnpm@latest --activate
  fi

  # nginx config
  sudo cp /var/www/html/rebours/nginx.conf /etc/nginx/sites-available/rebours
  sudo ln -sf /etc/nginx/sites-available/rebours /etc/nginx/sites-enabled/rebours
  sudo nginx -t && sudo systemctl reload nginx

  # systemd service
  sudo cp /var/www/html/rebours/deploy/rebours.service /etc/systemd/system/rebours.service
  sudo systemctl daemon-reload
  sudo systemctl enable rebours

  # permissions
  sudo chown -R ordinarthur:www-data /var/www/html/rebours

  echo "✅ VPS ready"
REMOTE

echo ""
echo "📝 Next steps:"
echo "   1. Create .env on the VPS:"
echo "      ssh $VPS 'nano $APP_DIR/.env'"
echo ""
echo "      DATABASE_URL=postgresql://user:pass@host:5432/rebours"
echo "      STRIPE_SECRET_KEY=sk_live_..."
echo "      STRIPE_WEBHOOK_SECRET=whsec_..."
echo "      DOMAIN=https://rebours.studio"
echo "      ADMIN_EMAIL=..."
echo "      ADMIN_PASSWORD=..."
echo "      COOKIE_SECRET=..."
echo ""
echo "   2. Deploy: bash deploy.sh"
echo ""
echo "   3. NPM: forward rebours.studio → 10.10.0.13:80"
