#!/bin/bash

# =================================================================
# Seraph3 Production Deployment Script (Laravel Mix)
# =================================================================
# This script automates the deployment process after git pull
# ensuring all CSS/JS assets and application changes take effect

set -e  # Exit on any error

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to run docker command with error handling
run_docker_cmd() {
    local cmd="$1"
    local description="$2"
    
    print_status "$description"
    if eval "$cmd"; then
        print_success "$description - Complete"
    else
        print_error "$description - Failed"
        exit 1
    fi
}

# Check prerequisites
check_prerequisites() {
    print_status "Checking prerequisites..."
    
    if ! command_exists docker; then
        print_error "Docker is not installed or not in PATH"
        exit 1
    fi
    
    if ! command_exists docker-compose; then
        print_error "Docker Compose is not installed or not in PATH"
        exit 1
    fi
    
    if [ ! -f "docker-compose.yml" ]; then
        print_error "docker-compose.yml not found. Are you in the project root?"
        exit 1
    fi
    
    print_success "Prerequisites check complete"
}

# Main deployment function
deploy() {
    echo -e "${BLUE}"
    echo "========================================"
    echo "  Seraph3 Production Deployment"
    echo "========================================"
    echo -e "${NC}"
    
    # Check prerequisites
    check_prerequisites
    
    # Step 1: Update code (optional - user can run this manually)
    if [[ "$1" == "--with-git-pull" ]]; then
        print_status "Pulling latest code from repository..."
        git pull origin main || {
            print_error "Git pull failed. Please resolve conflicts manually."
            exit 1
        }
        print_success "Code updated from repository"
    else
        print_warning "Skipping git pull (run with --with-git-pull to include)"
    fi
    
    # Step 2: Ensure containers are running
    print_status "Starting Docker containers..."
    docker-compose up -d
    
    # Wait for containers to be ready
    print_status "Waiting for containers to initialize..."
    sleep 10
    
    # Step 3: Clean and update PHP dependencies
    print_status "Cleaning Composer cache and vendor directory..."
    run_docker_cmd "docker-compose exec app composer clear-cache" \
                   "Clearing Composer cache"
    
    # Remove problematic vendor directories if they exist
    print_status "Removing potentially corrupted vendor packages..."
    docker-compose exec app bash -c "rm -rf vendor/calcinai/xero-php" 2>/dev/null || true
    docker-compose exec app bash -c "rm -rf vendor/composer" 2>/dev/null || true
    
    run_docker_cmd "docker-compose exec app composer install --no-dev --optimize-autoloader --no-interaction" \
                   "Updating PHP dependencies (Composer)"
    
    # Step 4: Update Node dependencies (only if package.json changed)
    if git diff HEAD~1 --name-only | grep -q "package.json"; then
        print_status "Cleaning npm cache..."
        docker-compose exec app npm cache clean --force 2>/dev/null || true
        run_docker_cmd "docker-compose exec app npm install" \
                       "Updating Node.js dependencies (package.json changed)"
    else
        print_status "Skipping npm install (package.json unchanged)"
    fi
    
    # Step 5: Build production assets (CRITICAL)
    print_status "Building production assets with Laravel Mix..."
    print_warning "This is CRITICAL - CSS/JS won't update without this step!"
    run_docker_cmd "docker-compose exec app npm run production" \
                   "Building optimized production assets"
    
    # Step 6: Clear and optimize Laravel caches
    print_status "Clearing Laravel caches..."
    run_docker_cmd "docker-compose exec app php artisan optimize:clear" \
                   "Clearing all Laravel caches"
    
    print_status "Optimizing Laravel for production..."
    run_docker_cmd "docker-compose exec app php artisan config:cache" \
                   "Caching configuration"
    run_docker_cmd "docker-compose exec app php artisan route:cache" \
                   "Caching routes"
    run_docker_cmd "docker-compose exec app php artisan view:cache" \
                   "Caching views"
    
    # Step 7: Run database migrations
    print_status "Running database migrations..."
    run_docker_cmd "docker-compose exec app php artisan migrate --force" \
                   "Applying database migrations"
    
    # Step 8: Restart PHP-FPM to ensure clean state
    print_status "Restarting application container..."
    docker-compose restart app
    
    # Step 9: Verify deployment
    print_status "Verifying deployment..."
    sleep 5
    
    # Check if containers are running
    if docker-compose ps | grep -q "Up"; then
        print_success "All containers are running"
    else
        print_error "Some containers are not running properly"
        print_status "Container status:"
        docker-compose ps
        exit 1
    fi
    
    # Final success message
    echo -e "${GREEN}"
    echo "========================================"
    echo "   🎉 DEPLOYMENT SUCCESSFUL! 🎉"
    echo "========================================"
    echo -e "${NC}"
    
    print_success "Assets built and optimized"
    print_success "Laravel caches refreshed"
    print_success "Database migrations applied"
    print_success "Application restarted"
    
    echo -e "${BLUE}"
    echo "Next steps:"
    echo "1. Test your application: https://yourdomain.com"
    echo "2. Check logs if needed: docker-compose logs app"
    echo "3. Monitor application performance"
    echo -e "${NC}"
}

# Help function
show_help() {
    echo "Seraph3 Production Deployment Script"
    echo ""
    echo "Usage:"
    echo "  ./deploy.sh                  Deploy with current code"
    echo "  ./deploy.sh --with-git-pull  Deploy and pull latest from git"
    echo "  ./deploy.sh --help          Show this help message"
    echo ""
    echo "What this script does:"
    echo "  1. Updates PHP dependencies (Composer)"
    echo "  2. Updates Node dependencies if needed"
    echo "  3. Builds production assets with Laravel Mix (CRITICAL)"
    echo "  4. Clears and optimizes Laravel caches"
    echo "  5. Runs database migrations"
    echo "  6. Restarts application"
    echo "  7. Verifies deployment"
    echo ""
    echo "IMPORTANT: This script ensures CSS/JS changes take effect in production!"
}

# Main script logic
case "$1" in
    --help)
        show_help
        ;;
    *)
        deploy "$1"
        ;;
esac 