#!/bin/bash

# Deployment script for manual-stock-management
# Usage: ./deploy.sh or npm run deploy

set -e  # Exit on error

# Configuration
SSH_KEY="$HOME/.ssh/manual-stock-management.pem"
SSH_USER="ubuntu"
SSH_HOST="54.166.124.217"
REMOTE_PATH="/var/www/stock-inventroy"
GIT_USERNAME="Jastin-vlogger"
GIT_TOKEN="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"

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

# Function to print colored messages
print_info() {
    echo -e "${BLUE}ℹ ${1}${NC}"
}

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

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

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

# Function to check if SSH key exists
check_ssh_key() {
    if [ ! -f "$SSH_KEY" ]; then
        print_error "SSH key not found at: $SSH_KEY"
        exit 1
    fi
}

# Function to deploy web (Next.js)
deploy_web() {
    print_info "Deploying Frontend (Next.js)..."
    
    ssh -i "$SSH_KEY" "$SSH_USER@$SSH_HOST" bash << EOF
        set -e
        cd /var/www/stock-inventroy
        echo "📥 Pulling latest code..."
        git config credential.helper store
        echo "https://${GIT_USERNAME}:${GIT_TOKEN}@github.com" > ~/.git-credentials
        git pull
        
        cd /var/www/stock-inventroy/web
        echo "📦 Installing dependencies..."
        npm install
        
        echo "🔨 Building application..."
        npm run build
        
        echo "🔄 Restarting PM2 process..."
        pm2 restart web
        
        echo "✅ Web deployment completed!"
EOF
    
    print_success "Frontend deployment completed!"
}

# Function to deploy API (Nest.js)
deploy_api() {
    print_info "Deploying API (Nest.js)..."
    
    ssh -i "$SSH_KEY" "$SSH_USER@$SSH_HOST" bash << EOF
        set -e
        cd /var/www/stock-inventroy
        echo "📥 Pulling latest code..."
        git config credential.helper store
        echo "https://${GIT_USERNAME}:${GIT_TOKEN}@github.com" > ~/.git-credentials
        git pull
        
        cd /var/www/stock-inventroy/api
        echo "📦 Installing dependencies..."
        npm install
        
        echo "🔨 Building application..."
        npm run build
        
        echo "🔄 Restarting PM2 process..."
        pm2 restart api
        
        echo "✅ API deployment completed!"
EOF
    
    print_success "API deployment completed!"
}

# Function to deploy extraction service (Python)
deploy_extraction() {
    print_info "Deploying Extraction Service (Python)..."
    
    ssh -i "$SSH_KEY" "$SSH_USER@$SSH_HOST" bash << EOF
        set -e
        cd /var/www/stock-inventroy
        echo "📥 Pulling latest code..."
        git config credential.helper store
        echo "https://${GIT_USERNAME}:${GIT_TOKEN}@github.com" > ~/.git-credentials
        git pull
        
        cd /var/www/stock-inventroy/extraction-service
        echo "🐍 Activating virtual environment..."
        source venv/bin/activate
        
        echo "📦 Installing dependencies..."
        pip install .
        
        echo "🔄 Restarting PM2 process..."
        pm2 restart extraction-service
        
        echo "✅ Extraction service deployment completed!"
EOF
    
    print_success "Extraction Service deployment completed!"
}

# Function to deploy all services
deploy_all() {
    print_info "Deploying all services..."
    echo ""
    
    deploy_web
    echo ""
    
    deploy_api
    echo ""
    
    deploy_extraction
    echo ""
    
    print_success "All services deployed successfully!"
}

# Main menu with multiselect
show_menu() {
    echo ""
    echo "╔════════════════════════════════════════╗"
    echo "║   Manual Stock Management Deployment  ║"
    echo "╚════════════════════════════════════════╝"
    echo ""
    echo "Select services to deploy (comma-separated):"
    echo ""
    echo "  1) Web (Next.js Frontend)"
    echo "  2) API (Nest.js Backend)"
    echo "  3) Extraction Service (Python)"
    echo "  4) All Services"
    echo ""
    echo "Examples: '1' or '1,2' or '1,2,3' or '4'"
    echo ""
    read -p "Enter your choices: " choices
    echo ""
}

# Function to process multiselect choices
process_choices() {
    local choices=$1
    local deployed=false
    
    # Remove spaces and split by comma
    IFS=',' read -ra SELECTED <<< "${choices// /}"
    
    # Check if "4" (All) is selected
    for choice in "${SELECTED[@]}"; do
        if [ "$choice" = "4" ]; then
            deploy_all
            return 0
        fi
    done
    
    # Deploy selected services
    for choice in "${SELECTED[@]}"; do
        case $choice in
            1)
                if [ "$deployed" = true ]; then
                    echo ""
                fi
                deploy_web
                deployed=true
                ;;
            2)
                if [ "$deployed" = true ]; then
                    echo ""
                fi
                deploy_api
                deployed=true
                ;;
            3)
                if [ "$deployed" = true ]; then
                    echo ""
                fi
                deploy_extraction
                deployed=true
                ;;
            *)
                print_error "Invalid choice: $choice. Skipping..."
                ;;
        esac
    done
    
    if [ "$deployed" = false ]; then
        print_error "No valid services selected."
        exit 1
    fi
}

# Main script execution
main() {
    check_ssh_key
    
    show_menu
    
    if [ -z "$choices" ]; then
        print_error "No choices entered."
        exit 1
    fi
    
    process_choices "$choices"
    
    echo ""
    print_success "Deployment process completed! 🚀"
}

# Run main function
main
