#!/bin/bash

# Microservices Setup Script
echo "🚀 Setting up my-backend..."

# Check Node.js version
REQUIRED_NODE="18.0.0"
CURRENT_NODE=$(node -v | sed 's/v//')

if [ "$(printf '%s\n' "$REQUIRED_NODE" "$CURRENT_NODE" | sort -V | head -n1)" != "$REQUIRED_NODE" ]; then
    echo "❌ Node.js version must be >= $REQUIRED_NODE. Current version: $CURRENT_NODE"
    exit 1
fi

# Check Docker
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

echo "✅ Prerequisites check passed"

# Create necessary directories
echo "📁 Creating directories..."
mkdir -p docker/volumes/mongodb
mkdir -p docker/volumes/redis
mkdir -p docker/volumes/uploads
mkdir -p docker/logs
mkdir -p services/auth-service/uploads
mkdir -p services/file-service/uploads

# Copy environment files
echo "⚙️  Setting up environment variables..."
if [ ! -f ".env" ]; then
    cp .env.example .env
    echo "📝 Created .env file from example"
else
    echo "📝 .env file already exists"
fi

if [ ! -f "docker/.env" ]; then
    cp docker/.env.example docker/.env
    echo "📝 Created docker/.env file from example"
else
    echo "📝 docker/.env file already exists"
fi

# Install dependencies
echo "📦 Installing dependencies..."

# Install root dependencies
npm install

# Install service dependencies
echo "📦 Installing service dependencies..."
cd api-gateway && npm install && cd ..
cd service-discovery && npm install && cd ..
cd services/auth-service && npm install && cd ../..
cd services/user-service && npm install && cd ../..
cd services/notification-service && npm install && cd ../..
cd services/file-service && npm install && cd ../..
cd services/payment-service && npm install && cd ../..
cd services/analytics-service && npm install && cd ../..

echo "✅ Setup completed successfully!"
echo ""
echo "Next steps:"
echo "1. Update .env and docker/.env files with your actual values"
echo "2. Run 'npm run start:dev' to start all services with Docker"
echo "3. Run 'npm run health-check' to verify all services are healthy"
echo ""
echo "Happy coding! 🎉"
