#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
#  Headless W (bwg CRM) — cPanel / VPS Setup Script
#  Run this inside cPanel Terminal or via SSH:
#    bash setup.sh
# ─────────────────────────────────────────────────────────────────────────────
set -e

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
info()    { echo -e "${BLUE}[INFO]${NC}  $1"; }
success() { echo -e "${GREEN}[OK]${NC}    $1"; }
warn()    { echo -e "${YELLOW}[WARN]${NC}  $1"; }
error()   { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="$APP_DIR/.env"

echo ""
echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Headless W — Deployment Setup          ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# ── 1. Node.js ────────────────────────────────────────────────────────────────
info "Checking Node.js..."
if ! command -v node &>/dev/null; then
  info "Node.js not found. Installing via nvm..."
  curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
  export NVM_DIR="$HOME/.nvm"
  # shellcheck disable=SC1091
  [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"
  nvm install 20
  nvm use 20
  nvm alias default 20
  success "Node.js $(node -v) installed via nvm"
else
  NODE_VER=$(node -e "process.exit(parseInt(process.version.slice(1)) < 18 ? 1 : 0)" 2>/dev/null && echo "ok" || echo "old")
  if [ "$NODE_VER" = "old" ]; then
    warn "Node.js $(node -v) is too old (need 18+). Installing 20 via nvm..."
    export NVM_DIR="$HOME/.nvm"
    [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" || (curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash && source "$HOME/.nvm/nvm.sh")
    nvm install 20 && nvm use 20 && nvm alias default 20
  fi
  success "Node.js $(node -v)"
fi

# ── 2. pnpm ───────────────────────────────────────────────────────────────────
info "Checking pnpm..."
if ! command -v pnpm &>/dev/null; then
  npm install -g pnpm@9
fi
success "pnpm $(pnpm -v)"

# ── 3. PM2 ────────────────────────────────────────────────────────────────────
info "Checking PM2..."
if ! command -v pm2 &>/dev/null; then
  npm install -g pm2
fi
success "PM2 $(pm2 -v)"

# ── 4. Create .env (auto-generated — no manual editing needed) ────────────────
echo ""
if [ -f "$ENV_FILE" ]; then
  warn ".env already exists — keeping it. Delete it and re-run to regenerate."
else
  info "Generating .env..."
  SESSION_SECRET_VAL=$(openssl rand -hex 32)
  # Password special chars are URL-encoded for the connection string:
  #   ^ = %5E  [ = %5B  * = %2A  ? = %3F  $ = %24
  cat > "$ENV_FILE" << ENVEOF
DATABASE_URL=mysql://h34dl355_devbostonw3b_whmcs:%5EPRW%5Bk%2A%3FpVzfe%244n@localhost/h34dl355_headtotoe
SESSION_SECRET=${SESSION_SECRET_VAL}
PORT=3099
NODE_ENV=production
ENVEOF
  success ".env created with database credentials and a fresh SESSION_SECRET"
fi

# Source .env
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

[ -z "$DATABASE_URL" ] && error "DATABASE_URL is not set in .env"
[ -z "$SESSION_SECRET" ] && error "SESSION_SECRET is not set in .env"
success ".env loaded"

# ── 5. Install dependencies ───────────────────────────────────────────────────
info "Installing dependencies..."
cd "$APP_DIR"
pnpm install --no-frozen-lockfile
success "Dependencies installed"

# ── 6. Database migration ─────────────────────────────────────────────────────
info "Running database migration..."
cd "$APP_DIR/lib/db"
DATABASE_URL="$DATABASE_URL" pnpm run push-force
success "Database schema up to date"
cd "$APP_DIR"

# ── 7. Build ──────────────────────────────────────────────────────────────────
info "Building API server..."
pnpm --filter @workspace/api-server run build
success "API server built"

info "Building frontend..."
pnpm --filter @workspace/proposa run build
success "Frontend built → artifacts/proposa/dist/public/"

# ── 8. PM2 start / restart ────────────────────────────────────────────────────
info "Starting API server with PM2..."
cd "$APP_DIR"
if pm2 list | grep -q "headless-w-api"; then
  pm2 restart headless-w-api
  success "API server restarted"
else
  pm2 start deploy/ecosystem.config.js
  success "API server started"
fi
pm2 save

# ── 9. Print next steps ───────────────────────────────────────────────────────
PORT="${PORT:-3099}"
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║  DEPLOYMENT COMPLETE                                         ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo "  API running on port $PORT"
echo "  Static files at: $APP_DIR/artifacts/proposa/dist/public/"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "  1. Set up Apache virtual host (see deploy/apache.conf)"
echo "     OR add the subdomain via cPanel → Subdomains"
echo "  2. In the app Settings page, set WHMCS URL to:"
echo "     http://localhost/bwg   (or wherever WHMCS is served locally)"
echo "  3. (Optional) Enable HTTPS via cPanel → Let's Encrypt SSL"
echo ""
pm2 status headless-w-api
