#!/bin/bash

#################################################
# Global Gala Production Deployment Script (DEPRECATED)
#
# ⚠️ DO NOT USE — this script is a relic from a pre-cPanel era.
#
# It assumes a Debian/Linux host with systemd, /var/www/showprima,
# www-data user, Redis queue driver, and npm Mix asset building —
# NONE of which apply to the actual GlobalGala cPanel deployment.
#
# The canonical production deploy path is:
#   scripts/deploy-prod.sh → scripts/deploy-dev.sh --branch=main
#
# Known bugs if you ignore this warning and run it anyway:
#   - Line 138: `composer install --no-dev` without clearing
#     bootstrap/cache/*.php first → hits the Telescope/IdeHelper
#     circular dependency we fixed in deploy-dev.sh (81a027b1)
#   - Line 146: `npm run production` is Laravel Mix syntax — if the
#     project is on Vite, this fails
#   - Line 204: Hardcoded `redis` queue driver — real deploy uses database
#   - Line 237: References scripts/validate-environment.php which doesn't exist
#   - No dev-only provider guard: config/app.php issue not addressed
#
# Kept only for reference / potential future systemd-based deploy.
#################################################

echo "ERROR: scripts/deploy-production.sh is deprecated and will not run." >&2
echo "Use scripts/deploy-prod.sh (which wraps scripts/deploy-dev.sh --branch=main)" >&2
echo "See the comment block at the top of this file for details." >&2
exit 1

set -e

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

# Configuration
APP_DIR="/var/www/showprima"
ENV_FILE=".env.production.complete"
BACKUP_DIR="/var/backups/showprima"
LOG_FILE="/var/log/showprima/deployment.log"

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Global Gala Production Deployment${NC}"
echo -e "${GREEN}========================================${NC}"

# Function to log messages
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOG_FILE
    echo -e "$1"
}

# Function to check prerequisites
check_prerequisites() {
    log_message "${YELLOW}Checking prerequisites...${NC}"
    
    # Check PHP version
    PHP_VERSION=$(php -v | head -n 1 | cut -d " " -f 2 | cut -d "." -f 1,2)
    if [[ $(echo "$PHP_VERSION >= 8.0" | bc) -eq 0 ]]; then
        log_message "${RED}❌ PHP 8.0+ required${NC}"
        exit 1
    fi
    log_message "${GREEN}✓ PHP version $PHP_VERSION${NC}"
    
    # Check Composer
    if ! command -v composer &> /dev/null; then
        log_message "${RED}❌ Composer not found${NC}"
        exit 1
    fi
    log_message "${GREEN}✓ Composer installed${NC}"
    
    # Check Node.js
    if ! command -v node &> /dev/null; then
        log_message "${RED}❌ Node.js not found${NC}"
        exit 1
    fi
    log_message "${GREEN}✓ Node.js installed${NC}"
    
    # Check Redis
    if command -v redis-cli &> /dev/null; then
        if redis-cli ping &> /dev/null; then
            log_message "${GREEN}✓ Redis server running${NC}"
        else
            log_message "${YELLOW}⚠️ Redis server not running${NC}"
        fi
    else
        log_message "${YELLOW}⚠️ Redis not installed${NC}"
    fi
    
    # Check MySQL
    if command -v mysql &> /dev/null; then
        log_message "${GREEN}✓ MySQL installed${NC}"
    else
        log_message "${RED}❌ MySQL not found${NC}"
        exit 1
    fi
}

# Function to backup current deployment
backup_current() {
    log_message "${YELLOW}Creating backup...${NC}"
    
    # Create backup directory if it doesn't exist
    mkdir -p $BACKUP_DIR
    
    # Create timestamped backup
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    BACKUP_NAME="backup_${TIMESTAMP}"
    
    # Backup database
    if [ -f "$APP_DIR/.env" ]; then
        source <(grep -E '^DB_' "$APP_DIR/.env" | sed 's/^/export /')
        mysqldump -h${DB_HOST} -u${DB_USERNAME} -p${DB_PASSWORD} ${DB_DATABASE} > "${BACKUP_DIR}/${BACKUP_NAME}.sql"
        log_message "${GREEN}✓ Database backed up${NC}"
    fi
    
    # Backup application files
    tar -czf "${BACKUP_DIR}/${BACKUP_NAME}_files.tar.gz" -C $APP_DIR . 2>/dev/null
    log_message "${GREEN}✓ Application files backed up${NC}"
}

# Function to setup environment
setup_environment() {
    log_message "${YELLOW}Setting up environment...${NC}"
    
    # Copy production environment file
    if [ -f "$ENV_FILE" ]; then
        cp $ENV_FILE $APP_DIR/.env
        log_message "${GREEN}✓ Environment file deployed${NC}"
    else
        log_message "${RED}❌ Production environment file not found${NC}"
        exit 1
    fi
    
    # Generate application key if needed
    if grep -q "REPLACE_WITH_GENERATED_KEY" "$APP_DIR/.env"; then
        cd $APP_DIR
        php artisan key:generate --force
        log_message "${GREEN}✓ Application key generated${NC}"
    fi
    
    # Set proper permissions
    chown -R www-data:www-data $APP_DIR
    chmod -R 755 $APP_DIR
    chmod -R 775 $APP_DIR/storage
    chmod -R 775 $APP_DIR/bootstrap/cache
    log_message "${GREEN}✓ Permissions set${NC}"
}

# Function to install dependencies
install_dependencies() {
    log_message "${YELLOW}Installing dependencies...${NC}"
    
    cd $APP_DIR
    
    # Install PHP dependencies
    composer install --no-dev --optimize-autoloader --no-interaction
    log_message "${GREEN}✓ PHP dependencies installed${NC}"
    
    # Install Node dependencies
    npm ci --production
    log_message "${GREEN}✓ Node dependencies installed${NC}"
    
    # Build assets
    npm run production
    log_message "${GREEN}✓ Assets compiled${NC}"
}

# Function to run migrations
run_migrations() {
    log_message "${YELLOW}Running database migrations...${NC}"
    
    cd $APP_DIR
    
    # Run migrations
    php artisan migrate --force
    log_message "${GREEN}✓ Migrations completed${NC}"
    
    # Seed database if needed
    # php artisan db:seed --force
}

# Function to optimize application
optimize_application() {
    log_message "${YELLOW}Optimizing application...${NC}"
    
    cd $APP_DIR
    
    # Clear and cache configuration
    php artisan config:clear
    php artisan config:cache
    log_message "${GREEN}✓ Configuration cached${NC}"
    
    # Clear and cache routes
    php artisan route:clear
    php artisan route:cache
    log_message "${GREEN}✓ Routes cached${NC}"
    
    # Clear and cache views
    php artisan view:clear
    php artisan view:cache
    log_message "${GREEN}✓ Views cached${NC}"
    
    # Optimize autoloader
    php artisan optimize
    log_message "${GREEN}✓ Application optimized${NC}"
}

# Function to setup queue workers
setup_queue_workers() {
    log_message "${YELLOW}Setting up queue workers...${NC}"
    
    # Create systemd service for queue worker
    cat > /etc/systemd/system/showprima-queue.service << EOF
[Unit]
Description=Global Gala Queue Worker
After=network.target

[Service]
User=www-data
Group=www-data
Restart=always
ExecStart=/usr/bin/php $APP_DIR/artisan queue:work redis --sleep=3 --tries=3 --timeout=60
StandardOutput=file:/var/log/showprima/queue.log
StandardError=file:/var/log/showprima/queue-error.log

[Install]
WantedBy=multi-user.target
EOF
    
    # Reload systemd and start service
    systemctl daemon-reload
    systemctl enable showprima-queue
    systemctl restart showprima-queue
    
    log_message "${GREEN}✓ Queue workers configured${NC}"
}

# Function to setup cron jobs
setup_cron_jobs() {
    log_message "${YELLOW}Setting up cron jobs...${NC}"
    
    # Add Laravel scheduler to crontab
    (crontab -l 2>/dev/null | grep -v "artisan schedule:run"; echo "* * * * * cd $APP_DIR && php artisan schedule:run >> /dev/null 2>&1") | crontab -
    
    log_message "${GREEN}✓ Cron jobs configured${NC}"
}

# Function to validate environment
validate_environment() {
    log_message "${YELLOW}Validating environment...${NC}"
    
    cd $APP_DIR
    
    # Run environment validation script
    php scripts/validate-environment.php
    
    if [ $? -eq 0 ]; then
        log_message "${GREEN}✓ Environment validation passed${NC}"
    else
        log_message "${RED}❌ Environment validation failed${NC}"
        exit 1
    fi
}

# Function to perform health check
health_check() {
    log_message "${YELLOW}Performing health check...${NC}"
    
    # Check if application responds
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/api/health)
    
    if [ "$HTTP_CODE" -eq 200 ]; then
        log_message "${GREEN}✓ Application health check passed${NC}"
    else
        log_message "${RED}❌ Application health check failed (HTTP $HTTP_CODE)${NC}"
        exit 1
    fi
}

# Main deployment process
main() {
    log_message "${GREEN}Starting deployment at $(date)${NC}"
    
    # Check prerequisites
    check_prerequisites
    
    # Put application in maintenance mode
    if [ -f "$APP_DIR/artisan" ]; then
        cd $APP_DIR
        php artisan down --message="System maintenance in progress" --retry=60
        log_message "${YELLOW}⚠️ Application in maintenance mode${NC}"
    fi
    
    # Backup current deployment
    backup_current
    
    # Pull latest code
    if [ -d "$APP_DIR/.git" ]; then
        cd $APP_DIR
        git pull origin main
        log_message "${GREEN}✓ Code updated${NC}"
    fi
    
    # Setup environment
    setup_environment
    
    # Install dependencies
    install_dependencies
    
    # Run migrations
    run_migrations
    
    # Optimize application
    optimize_application
    
    # Setup queue workers
    setup_queue_workers
    
    # Setup cron jobs
    setup_cron_jobs
    
    # Validate environment
    validate_environment
    
    # Bring application back online
    cd $APP_DIR
    php artisan up
    log_message "${GREEN}✓ Application back online${NC}"
    
    # Perform health check
    health_check
    
    # Clear OPcache
    if command -v cachetool &> /dev/null; then
        cachetool opcache:reset
        log_message "${GREEN}✓ OPcache cleared${NC}"
    fi
    
    log_message "${GREEN}========================================${NC}"
    log_message "${GREEN}✅ Deployment completed successfully!${NC}"
    log_message "${GREEN}========================================${NC}"
}

# Run main function
main