#!/bin/bash

# Fix AirwavePBX build issues

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}[INFO]${NC} Fixing AirwavePBX build issues..."

cd /opt/airwavepbx

# Install ALL dependencies (including devDependencies needed for build)
echo -e "${BLUE}[INFO]${NC} Installing all dependencies..."
npm install

# Now try to build again
echo -e "${BLUE}[INFO]${NC} Building AirwavePBX frontend..."
npm run build

if [ $? -eq 0 ]; then
    echo -e "${GREEN}[SUCCESS]${NC} Build completed successfully!"
    
    # Continue with the rest of the installation
    echo -e "${BLUE}[INFO]${NC} Starting AirwavePBX services..."
    
    # Load environment
    source /etc/airwavepbx/airwavepbx.env
    
    # Start services with PM2
    pm2 start ecosystem.config.js
    pm2 save
    pm2 startup systemd -u root --hp /root
    
    # Configure Nginx if not already done
    if [ ! -f /etc/nginx/sites-available/airwavepbx ]; then
        echo -e "${BLUE}[INFO]${NC} Configuring Nginx..."
        
        cat > /etc/nginx/sites-available/airwavepbx << EOF
server {
    listen 80;
    server_name $DOMAIN;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }

    location /api/ {
        proxy_pass http://localhost:3001/api/;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
    }

    location /ws {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
    }
}
EOF

        ln -sf /etc/nginx/sites-available/airwavepbx /etc/nginx/sites-enabled/
        rm -f /etc/nginx/sites-enabled/default
        nginx -t && systemctl reload nginx
    fi
    
    # Check service status
    sleep 5
    pm2 status
    
    echo -e "${GREEN}[SUCCESS]${NC} AirwavePBX installation completed!"
    echo
    echo "Access your system at: http://$DOMAIN"
    echo "Username: admin"
    echo "Password: admin"
    echo
    echo "To set up SSL, run: sudo certbot --nginx -d $DOMAIN"
    
else
    echo -e "${RED}[ERROR]${NC} Build failed. Checking for issues..."
    
    # Check if node_modules exists
    if [ ! -d "node_modules" ]; then
        echo -e "${RED}[ERROR]${NC} node_modules directory not found"
    fi
    
    # List what's in the directory
    echo -e "${BLUE}[INFO]${NC} Directory contents:"
    ls -la
fi