#!/bin/bash
# =============================================================================
# Staging Deployment Script
# =============================================================================
# Usage: ./scripts/deploy-staging.sh [--skip-build] [--skip-migrations]
#
# This script deploys the current develop branch to the staging environment.
# Run this on the staging server (pl.c2sgmbh.de) or via SSH.
# =============================================================================

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
PROJECT_DIR="/home/payload/payload-cms"
BRANCH="${DEPLOY_BRANCH:-develop}"  # Use env var or default to develop
LOG_FILE="/home/payload/logs/deploy-staging.log"

# Parse arguments
SKIP_BUILD=false
SKIP_MIGRATIONS=false
for arg in "$@"; do
  case $arg in
    --skip-build)
      SKIP_BUILD=true
      shift
      ;;
    --skip-migrations)
      SKIP_MIGRATIONS=true
      shift
      ;;
  esac
done

# Functions
log() {
  echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}

success() {
  echo -e "${GREEN}[SUCCESS]${NC} $1" | tee -a "$LOG_FILE"
}

warn() {
  echo -e "${YELLOW}[WARNING]${NC} $1" | tee -a "$LOG_FILE"
}

error() {
  echo -e "${RED}[ERROR]${NC} $1" | tee -a "$LOG_FILE"
  exit 1
}

# Ensure log directory exists
mkdir -p "$(dirname "$LOG_FILE")"

echo "=============================================="
echo "  Staging Deployment Script"
echo "  Environment: pl.c2sgmbh.de"
echo "=============================================="
echo ""

log "Starting staging deployment..."
log "Branch: $BRANCH"
log "Skip build: $SKIP_BUILD"
log "Skip migrations: $SKIP_MIGRATIONS"

# Change to project directory
cd "$PROJECT_DIR" || error "Could not change to project directory: $PROJECT_DIR"
log "Working directory: $(pwd)"

# Check current branch and stash changes
log "Checking git status..."
CURRENT_BRANCH=$(git branch --show-current)
if [ "$CURRENT_BRANCH" != "$BRANCH" ]; then
  warn "Currently on branch '$CURRENT_BRANCH', switching to '$BRANCH'"
fi

# Stash any local changes
if [ -n "$(git status --porcelain)" ]; then
  warn "Stashing local changes..."
  git stash --include-untracked
fi

# Fetch and reset to origin
log "Fetching latest code from origin/$BRANCH..."
git fetch origin "$BRANCH"
git checkout "$BRANCH"
git reset --hard "origin/$BRANCH"
success "Code updated to latest origin/$BRANCH"

# Show current commit
COMMIT_SHA=$(git rev-parse --short HEAD)
COMMIT_MSG=$(git log -1 --pretty=%s)
log "Current commit: $COMMIT_SHA - $COMMIT_MSG"

# Install dependencies
log "Installing dependencies..."
pnpm install --frozen-lockfile
success "Dependencies installed"

# Run migrations (unless skipped)
if [ "$SKIP_MIGRATIONS" = false ]; then
  log "Running database migrations..."
  pnpm payload migrate || warn "No migrations to run or migration failed"
else
  warn "Skipping migrations (--skip-migrations flag)"
fi

# Build (unless skipped)
if [ "$SKIP_BUILD" = false ]; then
  log "Building application..."

  # Stop PM2 to free memory for build
  pm2 stop payload 2>/dev/null || true
  pm2 stop queue-worker 2>/dev/null || true

  # Build with memory limit
  NODE_OPTIONS="--max-old-space-size=2048" pnpm build
  success "Build completed"
else
  warn "Skipping build (--skip-build flag)"
fi

# Restart services
log "Restarting PM2 services..."
pm2 restart payload --update-env 2>/dev/null || pm2 start ecosystem.config.cjs --only payload
pm2 restart queue-worker --update-env 2>/dev/null || pm2 start ecosystem.config.cjs --only queue-worker
success "Services restarted"

# Wait for service to start
log "Waiting for service to start..."
sleep 5

# Health check
log "Running health check..."
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/admin 2>/dev/null || echo "000")
if [ "$HTTP_STATUS" -ge 200 ] && [ "$HTTP_STATUS" -lt 400 ]; then
  success "Health check passed (HTTP $HTTP_STATUS)"
else
  warn "Health check returned HTTP $HTTP_STATUS"
fi

# Show PM2 status
echo ""
log "PM2 Status:"
pm2 status

# Summary
echo ""
echo "=============================================="
echo -e "${GREEN}  Staging Deployment Complete!${NC}"
echo "=============================================="
echo "  URL: https://pl.c2sgmbh.de"
echo "  Admin: https://pl.c2sgmbh.de/admin"
echo "  Commit: $COMMIT_SHA"
echo "  Time: $(date)"
echo "=============================================="

log "Deployment finished successfully"
