#!/usr/bin/env bash
# Ranchlands — one-shot server setup script
# Run from the project root: bash setup.sh
set -e

echo "=== Ranchlands Setup ==="

# 1. Wipe any stale node_modules (this is the fix for the pg/mysql2 mismatch)
echo ""
echo "[1/5] Clearing old node_modules..."
rm -rf node_modules server/node_modules client/node_modules shared/node_modules
rm -f package-lock.json server/package-lock.json client/package-lock.json shared/package-lock.json

# 2. Fresh install
echo ""
echo "[2/5] Installing dependencies..."
npm install

# 3. Check .env exists
echo ""
echo "[3/5] Checking environment config..."
if [ ! -f server/.env ]; then
  cp server/.env.example server/.env
  echo ""
  echo "  !! Created server/.env from template."
  echo "  !! Edit it now with your DB credentials and JWT secrets, then re-run this script."
  echo ""
  exit 1
fi

# Quick check that DB_PASSWORD has been set
if grep -q "your_password_here" server/.env; then
  echo ""
  echo "  !! server/.env still has placeholder values."
  echo "  !! Edit server/.env and set your real DB_PASSWORD and JWT secrets."
  echo ""
  exit 1
fi

# 4. Migrate + seed
echo ""
echo "[4/5] Running database migrations..."
npm run db:migrate

echo ""
echo "[4/5] Seeding database..."
npm run db:seed

# 5. Build frontend
echo ""
echo "[5/5] Building frontend..."
npm run build

echo ""
echo "=== Setup complete! ==="
echo ""
echo "Next steps:"
echo "  1. Install PM2 if not already:  npm install -g pm2"
echo "  2. Start the server:            pm2 start ecosystem.config.js --env production"
echo "  3. Copy frontend build:         sudo cp -r client/dist/* /var/www/ranchlands-web/"
echo "  4. Enable NGINX site:           see DEPLOY.md"
echo ""
