#!/bin/bash

# UrbanGamers VPS Fix Script
# Run this on your VPS to fix deployment issues

echo "🔧 Starting VPS troubleshooting and fix..."

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

# Find project directory
PROJECT_DIR=$(find /var/www /home -name "package.json" -type f 2>/dev/null | grep -v node_modules | head -1 | xargs dirname)

if [ -z "$PROJECT_DIR" ]; then
    echo -e "${RED}Error: Could not find project directory.${NC}"
    echo "Please run this script from your project directory or specify PROJECT_DIR"
    exit 1
fi

echo -e "${GREEN}Found project at: $PROJECT_DIR${NC}"
cd "$PROJECT_DIR"

# Step 1: Check Node.js and npm
echo -e "\n${YELLOW}[1/10] Checking Node.js and npm...${NC}"
node -v
npm -v

# Step 2: Install missing dependencies (next-intl is critical!)
echo -e "\n${YELLOW}[2/10] Installing/updating dependencies...${NC}"
npm install next-intl@latest @formatjs/intl-localematcher --save

# Step 3: Check for .env.local
echo -e "\n${YELLOW}[3/10] Checking environment variables...${NC}"
if [ ! -f .env.local ]; then
    echo -e "${RED}WARNING: .env.local not found!${NC}"
    echo "Make sure your environment variables are set up."
else
    echo -e "${GREEN}.env.local exists${NC}"
fi

# Step 4: Clean old build
echo -e "\n${YELLOW}[4/10] Cleaning old build...${NC}"
rm -rf .next
rm -rf node_modules/.cache
echo -e "${GREEN}Clean complete${NC}"

# Step 5: Rebuild application
echo -e "\n${YELLOW}[5/10] Building application...${NC}"
NODE_ENV=production npm run build

if [ $? -ne 0 ]; then
    echo -e "${RED}Build failed! Check errors above.${NC}"
    exit 1
fi

# Step 6: Verify build
echo -e "\n${YELLOW}[6/10] Verifying build...${NC}"
if [ ! -f .next/BUILD_ID ]; then
    echo -e "${RED}ERROR: Build failed - BUILD_ID not found!${NC}"
    exit 1
fi
echo -e "${GREEN}Build verified: $(cat .next/BUILD_ID)${NC}"

# Step 7: Stop PM2 processes
echo -e "\n${YELLOW}[7/10] Stopping PM2 processes...${NC}"
pm2 stop urbangamers || true
pm2 delete urbangamers || true
sleep 2

# Step 8: Start with PM2
echo -e "\n${YELLOW}[8/10] Starting application with PM2...${NC}"
pm2 start ecosystem.config.js --env production
pm2 save

# Step 9: Check PM2 status
echo -e "\n${YELLOW}[9/10] Checking PM2 status...${NC}"
pm2 status
pm2 logs urbangamers --lines 20

# Step 10: Test application
echo -e "\n${YELLOW}[10/10] Testing application...${NC}"
sleep 3
curl -I http://localhost:3000 2>/dev/null | head -1 || echo -e "${RED}Application not responding on port 3000${NC}"

# Step 11: Check Nginx
echo -e "\n${YELLOW}[11] Checking Nginx...${NC}"
systemctl status nginx --no-pager | head -5

echo -e "\n${GREEN}✅ Fix script completed!${NC}"
echo -e "\nNext steps:"
echo "1. Check PM2 logs: pm2 logs urbangamers --lines 50"
echo "2. Check error logs: pm2 logs urbangamers --err --lines 50"
echo "3. Check if port 3000 is listening: netstat -tuln | grep 3000"
echo "4. Test website: curl http://localhost:3000"

