#!/bin/bash
# =============================================================================
# Production Deployment Script for M1 ERP
# =============================================================================
# This script handles full deployment from dev to production including:
# - Code sync from GitHub
# - Database migration tracking
# - Backup and rollback capability
# =============================================================================

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

# Configuration
PROD_SERVER="merph.mavrixone"
PROD_USER="mavrixone"
PROD_PATH="/Users/mavrixone/LocalPHPStorm/m1_erp_web"
DB_NAME="brickwal_m1_ds"
DB_USER="rpmbbu"
DB_PASS="z8468RPMerkuri123!"

# SSH command (uses SSH keys - run ssh-copy-id first if needed)
SSH_CMD="ssh $PROD_USER@$PROD_SERVER"
SCP_CMD="scp"

# Functions
print_header() {
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}\n"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

# =============================================================================
# STEP 1: Pre-deployment checks
# =============================================================================
check_local_state() {
    print_header "Step 1: Pre-deployment Checks"
    
    # Check if we're in the right directory
    if [[ ! -f "public/index.php" ]]; then
        print_error "Not in m1_erp_web root directory"
        exit 1
    fi
    print_success "In correct directory"
    
    # Check git status
    if [[ -n $(git status -s) ]]; then
        print_warning "You have uncommitted changes:"
        git status -s
        read -p "Continue anyway? (y/n) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    else
        print_success "No uncommitted changes"
    fi
    
    # Check if pushed to GitHub
    LOCAL=$(git rev-parse @)
    REMOTE=$(git rev-parse @{u})
    if [[ $LOCAL != $REMOTE ]]; then
        print_error "Local branch is not in sync with remote"
        echo "Run: cd /admin/system-scripts and use 'Push to GitHub'"
        exit 1
    fi
    print_success "Code is pushed to GitHub"
}

# =============================================================================
# STEP 2: Get list of migrations to run
# =============================================================================
get_pending_migrations() {
    print_header "Step 2: Checking Migrations"
    
    # Get list of all local migrations
    LOCAL_MIGRATIONS=$(ls database/migrations/*.sql 2>/dev/null | grep -E "^database/migrations/[0-9]+" | sort -V || true)
    
    if [[ -z "$LOCAL_MIGRATIONS" ]]; then
        print_warning "No migrations found"
        return
    fi
    
    # Count migrations
    MIGRATION_COUNT=$(echo "$LOCAL_MIGRATIONS" | wc -l | tr -d ' ')
    print_success "Found $MIGRATION_COUNT migration files locally"
    
    # Show recent migrations
    echo -e "\n${YELLOW}Recent migrations:${NC}"
    echo "$LOCAL_MIGRATIONS" | tail -10 | sed 's/database\/migrations\//  /'
}

# =============================================================================
# STEP 3: Generate deployment package
# =============================================================================
create_deployment_script() {
    print_header "Step 3: Creating Deployment Script"
    
    DEPLOY_SCRIPT="/tmp/deploy_migrations_$(date +%Y%m%d_%H%M%S).sh"
    
    cat > "$DEPLOY_SCRIPT" << 'DEPLOY_EOF'
#!/bin/bash
# Auto-generated deployment script
# Generated: $(date)

set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

DB_NAME="brickwal_m1_ds"
DB_USER="brickwal_m1_ds"
DB_PASS="zyxyzRPMMerkurim1DS123!"

# Find MySQL binaries
if command -v mysqldump >/dev/null 2>&1; then
    MYSQLDUMP="mysqldump"
    MYSQL="mysql"
elif [ -f "/usr/local/mysql/bin/mysqldump" ]; then
    MYSQLDUMP="/usr/local/mysql/bin/mysqldump"
    MYSQL="/usr/local/mysql/bin/mysql"
elif [ -f "/opt/homebrew/bin/mysqldump" ]; then
    MYSQLDUMP="/opt/homebrew/bin/mysqldump"
    MYSQL="/opt/homebrew/bin/mysql"
else
    echo -e "${YELLOW}⚠ MySQL not found - skipping backup${NC}"
    MYSQLDUMP=""
    MYSQL="mysql"  # Hope it's in PATH
fi

echo -e "${YELLOW}Starting Production Deployment${NC}"
echo "Time: $(date)"
echo ""

# Navigate to production directory
cd PROD_PATH_PLACEHOLDER

# Backup database
if [[ -n "$MYSQLDUMP" ]]; then
    echo -e "\n${YELLOW}Creating database backup...${NC}"
    BACKUP_FILE="backups/db_backup_$(date +%Y%m%d_%H%M%S).sql"
    mkdir -p backups
    $MYSQLDUMP -u $DB_USER -p$DB_PASS $DB_NAME > $BACKUP_FILE
    if [[ $? -eq 0 ]]; then
        echo -e "${GREEN}✓ Database backed up to $BACKUP_FILE${NC}"
    else
        echo -e "${RED}✗ Database backup failed!${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠ Skipping database backup (mysqldump not found)${NC}"
    BACKUP_FILE="N/A"
fi

# Pull latest code
echo -e "\n${YELLOW}Pulling latest code from GitHub...${NC}"
git fetch origin
git reset --hard origin/main
echo -e "${GREEN}✓ Code updated${NC}"

# Get list of applied migrations
echo -e "\n${YELLOW}Checking migration status...${NC}"
APPLIED_MIGRATIONS=$(mysql -u $DB_USER -p$DB_PASS -D $DB_NAME -s -N -e "
    SELECT migration_file FROM migration_log WHERE status='success' ORDER BY migration_number;
" 2>/dev/null || echo "")

if [[ -z "$APPLIED_MIGRATIONS" ]]; then
    echo -e "${YELLOW}⚠ migration_log table not found or empty. Will apply all migrations.${NC}"
fi

# Run pending migrations
echo -e "\n${YELLOW}Running migrations...${NC}"
MIGRATION_COUNT=0
for migration_file in database/migrations/[0-9]*.sql; do
    if [[ ! -f "$migration_file" ]]; then
        continue
    fi
    
    filename=$(basename "$migration_file")
    
    # Check if already applied
    if echo "$APPLIED_MIGRATIONS" | grep -q "^$filename$"; then
        echo -e "  ${GREEN}✓${NC} $filename (already applied)"
        continue
    fi
    
    # Apply migration
    echo -e "  ${YELLOW}Running${NC} $filename..."
    START_TIME=$(date +%s%3N)
    
    if mysql -u $DB_USER -p$DB_PASS $DB_NAME < "$migration_file" 2>&1; then
        END_TIME=$(date +%s%3N)
        EXEC_TIME=$((END_TIME - START_TIME))
        
        # Extract migration number
        MIGRATION_NUM=$(echo "$filename" | grep -oE "^[0-9]+" || echo "0")
        
        # Log to migration_log
        mysql -u $DB_USER -p$DB_PASS $DB_NAME -e "
            INSERT INTO migration_log 
            (migration_number, migration_file, applied_by, status, execution_time_ms)
            VALUES ($MIGRATION_NUM, '$filename', 1, 'success', $EXEC_TIME)
            ON DUPLICATE KEY UPDATE applied_at = CURRENT_TIMESTAMP;
        " 2>/dev/null || true
        
        echo -e "  ${GREEN}✓${NC} $filename (${EXEC_TIME}ms)"
        MIGRATION_COUNT=$((MIGRATION_COUNT + 1))
    else
        echo -e "  ${RED}✗ Failed to apply $filename${NC}"
        
        # Log failure
        mysql -u $DB_USER -p$DB_PASS $DB_NAME -e "
            INSERT INTO migration_log 
            (migration_number, migration_file, applied_by, status, error_message)
            VALUES ($MIGRATION_NUM, '$filename', 1, 'failed', 'See deployment logs')
            ON DUPLICATE KEY UPDATE status='failed', applied_at = CURRENT_TIMESTAMP;
        " 2>/dev/null || true
        
        echo -e "\n${RED}Deployment failed. Database backup available at: $BACKUP_FILE${NC}"
        exit 1
    fi
done

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}Deployment Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "Migrations applied: $MIGRATION_COUNT"
echo -e "Backup location: $BACKUP_FILE"
echo -e "Time: $(date)"
echo ""

DEPLOY_EOF

    # Replace placeholder with actual path
    sed -i '' "s|PROD_PATH_PLACEHOLDER|$PROD_PATH|g" "$DEPLOY_SCRIPT"
    
    chmod +x "$DEPLOY_SCRIPT"
    print_success "Deployment script created: $DEPLOY_SCRIPT"
}

# =============================================================================
# STEP 4: Deploy to production
# =============================================================================
deploy_to_production() {
    print_header "Step 4: Deploying to Production"
    
    print_warning "This will deploy to production server: $PROD_SERVER"
    read -p "Continue? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_warning "Deployment cancelled"
        exit 0
    fi
    
    # Copy script to production
    echo "Copying deployment script to production..."
    $SCP_CMD "$DEPLOY_SCRIPT" "$PROD_USER@$PROD_SERVER:/tmp/"
    
    # Execute on production
    echo -e "\n${YELLOW}Executing deployment on production...${NC}\n"
    $SSH_CMD "bash /tmp/$(basename $DEPLOY_SCRIPT)"
    
    if [[ $? -eq 0 ]]; then
        print_success "Deployment completed successfully!"
    else
        print_error "Deployment failed. Check logs above."
        exit 1
    fi
}

# =============================================================================
# STEP 5: Post-deployment verification
# =============================================================================
verify_deployment() {
    print_header "Step 5: Verification"
    
    echo "Checking production status..."
    $SSH_CMD << 'VERIFY_EOF'
        cd PROD_PATH_PLACEHOLDER
        
        # Check git status
        echo "Git status:"
        git log -1 --oneline
        
        # Check migration count
        echo -e "\nMigration status:"
        mysql -u brickwal_m1_ds -pzyxyzRPMMerkurim1DS123! brickwal_m1_ds -e "
            SELECT COUNT(*) as applied_migrations FROM migration_log WHERE status='success';
            SELECT migration_file, applied_at FROM migration_log ORDER BY applied_at DESC LIMIT 5;
        "
VERIFY_EOF
    
    print_success "Verification complete"
}

# =============================================================================
# Main execution
# =============================================================================
main() {
    clear
    print_header "M1 ERP Production Deployment"
    echo "Target: $PROD_SERVER"
    echo "Database: $DB_NAME"
    echo ""
    
    check_local_state
    get_pending_migrations
    create_deployment_script
    
    echo -e "\n${YELLOW}Deployment script ready at:${NC} $DEPLOY_SCRIPT"
    echo -e "${YELLOW}You can:${NC}"
    echo -e "  1. Run full deployment: ${GREEN}$0 --execute${NC}"
    echo -e "  2. Review script first: ${GREEN}cat $DEPLOY_SCRIPT${NC}"
    echo -e "  3. Deploy manually: ${GREEN}bash $DEPLOY_SCRIPT${NC}"
    echo ""
    
    if [[ "$1" == "--execute" ]]; then
        deploy_to_production
        verify_deployment
    else
        read -p "Deploy now? (y/n) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            deploy_to_production
            verify_deployment
        fi
    fi
    
    print_success "Done!"
}

# Run main
main "$@"
