#!/bin/bash
# build-changed.sh - Build and deploy only changed services
# Usage: ./build-changed.sh [service-name] or ./build-changed.sh --detect

set -e

REGISTRY="your-registry.com/nxtgauge"
VERSION=${VERSION:-$(git rev-parse --short HEAD)}

# Services list
SERVICES=(
  "gateway:apps/gateway"
  "users:apps/users"
  "companies:apps/companies"
  "job_seekers:apps/job_seekers"
  "customers:apps/customers"
  "photographers:apps/photographers"
  "makeup_artists:apps/makeup_artists"
  "tutors:apps/tutors"
  "developers:apps/developers"
  "video_editors:apps/video_editors"
  "graphic_designers:apps/graphic_designers"
  "social_media_managers:apps/social_media_managers"
  "fitness_trainers:apps/fitness_trainers"
  "catering_services:apps/catering_services"
  "ugc_content_creators:apps/ugc_content_creators"
  "employees:apps/employees"
  "payments:apps/payments"
  "cron:apps/cron"
)

build_service() {
  local service=$1
  local tag="${REGISTRY}/${service}:${VERSION}"
  local latest="${REGISTRY}/${service}:latest"
  
  echo "🔨 Building ${service}..."
  
  docker build \
    --build-arg SERVICE_NAME=${service} \
    -f Dockerfile.optimized \
    -t ${tag} \
    -t ${latest} \
    .
  
  echo "📤 Pushing ${service}..."
  docker push ${tag}
  docker push ${latest}
  
  echo "✅ ${service} built and pushed"
}

# If specific service provided
if [ "$1" != "--detect" ] && [ -n "$1" ]; then
  build_service "$1"
  exit 0
fi

# Auto-detect changed services
if [ "$1" == "--detect" ]; then
  echo "🔍 Detecting changed services..."
  
  # Get changed files from last commit
  CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD)
  
  # Check if shared crates changed
  SHARED_CHANGED=false
  if echo "$CHANGED_FILES" | grep -q "^crates/"; then
    SHARED_CHANGED=true
    echo "⚠️  Shared crates changed - will rebuild all services"
  fi
  
  # Check each service
  for service_info in "${SERVICES[@]}"; do
    IFS=':' read -r service path <<< "$service_info"
    
    if [ "$SHARED_CHANGED" = true ] || echo "$CHANGED_FILES" | grep -q "^${path}/"; then
      build_service "$service"
    else
      echo "⏭️  ${service} - no changes, skipping"
    fi
  done
fi

echo "🎉 Build complete!"
