#!/bin/bash
# build-all.sh - Build all nxtgauge backend services and push to registry
# Usage: ./scripts/build-all.sh [TAG]

set -e

REGISTRY="registry.nxtgauge.com"
TAG=${1:-$(git rev-parse --short HEAD)}
DOCKERFILE="Dockerfile.simple"

echo "============================================"
echo "🚀 NXTGAUGE Full Rebuild Script"
echo "============================================"
echo "Registry: ${REGISTRY}"
echo "Tag: ${TAG}"
echo "Dockerfile: ${DOCKERFILE}"
echo ""

# Services list with underscores (matching Cargo.toml bin names)
SERVICES=(
  "gateway"
  "users"
  "companies"
  "job_seekers"
  "customers"
  "photographers"
  "makeup_artists"
  "tutors"
  "developers"
  "video_editors"
  "graphic_designers"
  "social_media_managers"
  "fitness_trainers"
  "catering_services"
  "ugc_content_creators"
  "employees"
  "payments"
  "jobs"
  "leads"
  "cron"
)

# Also need service names with hyphens for image names
declare -A SERVICE_IMAGE_NAMES=(
  ["gateway"]="nxtgauge-rust-gateway"
  ["users"]="nxtgauge-rust-users"
  ["companies"]="nxtgauge-rust-companies"
  ["job_seekers"]="nxtgauge-rust-job-seekers"
  ["customers"]="nxtgauge-rust-customers"
  ["photographers"]="nxtgauge-rust-photographers"
  ["makeup_artists"]="nxtgauge-rust-makeup-artists"
  ["tutors"]="nxtgauge-rust-tutors"
  ["developers"]="nxtgauge-rust-developers"
  ["video_editors"]="nxtgauge-rust-video-editors"
  ["graphic_designers"]="nxtgauge-rust-graphic-designers"
  ["social_media_managers"]="nxtgauge-rust-social-media-managers"
  ["fitness_trainers"]="nxtgauge-rust-fitness-trainers"
  ["catering_services"]="nxtgauge-rust-catering-services"
  ["ugc_content_creators"]="nxtgauge-rust-ugc-content-creators"
  ["employees"]="nxtgauge-rust-employees"
  ["payments"]="nxtgauge-rust-payments"
  ["jobs"]="nxtgauge-rust-jobs"
  ["leads"]="nxtgauge-rust-leads"
  ["cron"]="nxtgauge-rust-cron"
)

TOTAL=${#SERVICES[@]}
CURRENT=0

build_service() {
  local service=$1
  local image_name=${SERVICE_IMAGE_NAMES[$service]}
  local tag="${REGISTRY}/${image_name}:${TAG}"
  local latest="${REGISTRY}/${image_name}:latest"

  CURRENT=$((CURRENT + 1))
  echo ""
  echo "[$CURRENT/$TOTAL] Building ${image_name}..."
  echo "   Service: ${service}"
  echo "   Tag: ${tag}"

  # Build
  docker build \
    --build-arg SERVICE_NAME=${service} \
    -f ${DOCKERFILE} \
    -t ${tag} \
    -t ${latest} \
    . 2>&1 | tail -5

  # Push
  echo "   Pushing..."
  docker push ${tag}
  docker push ${latest}

  echo "   ✅ ${image_name} complete"
}

# Build all services
for service in "${SERVICES[@]}"; do
  build_service "${service}"
done

echo ""
echo "============================================"
echo "🎉 All services built and pushed!"
echo "============================================"
echo "Tag used: ${TAG}"
echo ""
echo "Update kustomization.yaml with:"
for service in "${SERVICES[@]}"; do
  local image_name=${SERVICE_IMAGE_NAMES[$service]}
  echo "  ${image_name}: ${TAG}"
done
