#!/usr/bin/env bash
# Build multi-platform Docker image (linux/amd64 + linux/arm64)
# Usage:
#   ./docker-build.sh              → build + load locally (single platform)
#   ./docker-build.sh --push       → build + push to Docker Hub

set -euo pipefail

# ── Config ────────────────────────────────────────────────────
IMAGE_NAME="renolation/english-toeic"
IMAGE_TAG="${IMAGE_TAG:-latest}"
REGISTRY="${REGISTRY:-}"
PLATFORMS="linux/amd64,linux/arm64"
BUILDER_NAME="multiarch-builder"
ENV_FILE=".env"

# ── Load env vars from .env ───────────────────────────────────
if [[ ! -f "$ENV_FILE" ]]; then
  echo "❌  $ENV_FILE not found. Copy .env.example and fill in values."
  exit 1
fi

# Load all vars from .env (set -a auto-exports every assignment)
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

: "${VITE_SUPABASE_URL:?VITE_SUPABASE_URL is required in .env}"
: "${VITE_SUPABASE_ANON_KEY:?VITE_SUPABASE_ANON_KEY is required in .env}"

FULL_IMAGE="${IMAGE_NAME}:${IMAGE_TAG}"

# ── Parse flags ───────────────────────────────────────────────
PUSH=false
for arg in "$@"; do
  case $arg in
    --push) PUSH=true ;;
  esac
done

echo "🔧  Image : $FULL_IMAGE"
echo "🖥️   Platforms: $PLATFORMS"
echo ""

# ── Ensure buildx builder exists ─────────────────────────────
if ! docker buildx inspect "$BUILDER_NAME" &>/dev/null; then
  echo "📦  Creating buildx builder: $BUILDER_NAME"
  docker buildx create --name "$BUILDER_NAME" --driver docker-container --bootstrap
fi
docker buildx use "$BUILDER_NAME"

# ── Build ─────────────────────────────────────────────────────
BUILD_ARGS=(
  --platform "$PLATFORMS"
  --build-arg "VITE_SUPABASE_URL=${VITE_SUPABASE_URL}"
  --build-arg "VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}"
  --build-arg "VITE_SUPABASE_PUBLISHABLE_KEY=${VITE_SUPABASE_PUBLISHABLE_KEY:-}"
  --tag "$FULL_IMAGE"
  --file Dockerfile
)

if $PUSH; then
  echo "🚀  Building and pushing to registry..."
  docker buildx build "${BUILD_ARGS[@]}" --push .
  echo ""
  echo "✅  Pushed: $FULL_IMAGE"
else
  # --load only works for single platform; build amd64 locally by default
  echo "🏗️   Building for local use (linux/amd64)..."
  docker buildx build \
    --platform linux/amd64 \
    --build-arg "VITE_SUPABASE_URL=${VITE_SUPABASE_URL}" \
    --build-arg "VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}" \
    --build-arg "VITE_SUPABASE_PUBLISHABLE_KEY=${VITE_SUPABASE_PUBLISHABLE_KEY:-}" \
    --tag "$FULL_IMAGE" \
    --file Dockerfile \
    --load \
    .
  echo ""
  echo "✅  Built locally: $FULL_IMAGE"
  echo "   Run with: docker compose up  (or)  docker run -p 3000:80 $FULL_IMAGE"
fi
