#!/bin/bash
set -euo pipefail

# ── Configuration ──
REGISTRY="icn.ocir.io/idyhsdamac8c/tasteby"
NAMESPACE="tasteby"
PLATFORM="linux/arm64"

# ── Parse arguments ──
TARGET="all"   # all | backend | frontend
MESSAGE=""
DRY_RUN=false

while [[ $# -gt 0 ]]; do
  case $1 in
    --backend-only) TARGET="backend"; shift ;;
    --frontend-only) TARGET="frontend"; shift ;;
    --dry-run) DRY_RUN=true; shift ;;
    -m) MESSAGE="$2"; shift 2 ;;
    *) MESSAGE="$1"; shift ;;
  esac
done

# ── Determine next version ──
LATEST_TAG=$(git tag --sort=-v:refname | grep '^v' | head -1 2>/dev/null || echo "v0.1.0")
MAJOR=$(echo "$LATEST_TAG" | cut -d. -f1)
MINOR=$(echo "$LATEST_TAG" | cut -d. -f2)
PATCH=$(echo "$LATEST_TAG" | cut -d. -f3)
NEXT_PATCH=$((PATCH + 1))
TAG="${MAJOR}.${MINOR}.${NEXT_PATCH}"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  Deploying Tasteby ${TAG}"
echo "  Target: ${TARGET}"
echo "  Message: ${MESSAGE:-<none>}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if $DRY_RUN; then
  echo "[DRY RUN] Would build & push images, apply K8s manifests, create git tag."
  exit 0
fi

cd "$(git rev-parse --show-toplevel)"

# ── Build & Push ──
if [[ "$TARGET" == "all" || "$TARGET" == "backend" ]]; then
  echo ""
  echo "▶ Building backend image..."
  docker build --platform "$PLATFORM" \
    -t "$REGISTRY/backend:$TAG" \
    -t "$REGISTRY/backend:latest" \
    backend-java/
  echo "▶ Pushing backend image..."
  docker push "$REGISTRY/backend:$TAG"
  docker push "$REGISTRY/backend:latest"
fi

if [[ "$TARGET" == "all" || "$TARGET" == "frontend" ]]; then
  echo ""
  echo "▶ Building frontend image..."

  # Read build args from env or .env file
  MAPS_KEY="${NEXT_PUBLIC_GOOGLE_MAPS_API_KEY:-}"
  CLIENT_ID="${NEXT_PUBLIC_GOOGLE_CLIENT_ID:-}"
  NAVER_MAP_ID="${NEXT_PUBLIC_NAVER_MAP_CLIENT_ID:-}"

  if [[ -f frontend/.env.local ]]; then
    MAPS_KEY="${MAPS_KEY:-$(grep NEXT_PUBLIC_GOOGLE_MAPS_API_KEY frontend/.env.local 2>/dev/null | cut -d= -f2)}"
    CLIENT_ID="${CLIENT_ID:-$(grep NEXT_PUBLIC_GOOGLE_CLIENT_ID frontend/.env.local 2>/dev/null | cut -d= -f2)}"
    NAVER_MAP_ID="${NAVER_MAP_ID:-$(grep NEXT_PUBLIC_NAVER_MAP_CLIENT_ID frontend/.env.local 2>/dev/null | cut -d= -f2)}"
  fi

  docker build --platform "$PLATFORM" \
    --build-arg NEXT_PUBLIC_GOOGLE_MAPS_API_KEY="$MAPS_KEY" \
    --build-arg NEXT_PUBLIC_GOOGLE_CLIENT_ID="$CLIENT_ID" \
    --build-arg NEXT_PUBLIC_NAVER_MAP_CLIENT_ID="$NAVER_MAP_ID" \
    -t "$REGISTRY/frontend:$TAG" \
    -t "$REGISTRY/frontend:latest" \
    frontend/
  echo "▶ Pushing frontend image..."
  docker push "$REGISTRY/frontend:$TAG"
  docker push "$REGISTRY/frontend:latest"
fi

# ── Deploy to K8s ──
echo ""
echo "▶ Updating K8s deployments..."

if [[ "$TARGET" == "all" || "$TARGET" == "backend" ]]; then
  kubectl set image deployment/backend \
    backend="$REGISTRY/backend:$TAG" \
    -n "$NAMESPACE"
  echo "  Waiting for backend rollout..."
  kubectl rollout status deployment/backend -n "$NAMESPACE" --timeout=180s
fi

if [[ "$TARGET" == "all" || "$TARGET" == "frontend" ]]; then
  kubectl set image deployment/frontend \
    frontend="$REGISTRY/frontend:$TAG" \
    -n "$NAMESPACE"
  echo "  Waiting for frontend rollout..."
  kubectl rollout status deployment/frontend -n "$NAMESPACE" --timeout=120s
fi

# ── Git tag ──
echo ""
echo "▶ Creating git tag ${TAG}..."

TAG_MESSAGE="Deploy ${TAG}"
if [[ -n "$MESSAGE" ]]; then
  TAG_MESSAGE="${TAG_MESSAGE}: ${MESSAGE}"
fi

# Include changed components
COMPONENTS=""
[[ "$TARGET" == "all" || "$TARGET" == "backend" ]] && COMPONENTS="backend"
[[ "$TARGET" == "all" || "$TARGET" == "frontend" ]] && COMPONENTS="${COMPONENTS:+$COMPONENTS, }frontend"
TAG_MESSAGE="${TAG_MESSAGE}

Components: ${COMPONENTS}
Images:
$([ "$TARGET" == "all" ] || [ "$TARGET" == "backend" ] && echo "  - ${REGISTRY}/backend:${TAG}")
$([ "$TARGET" == "all" ] || [ "$TARGET" == "frontend" ] && echo "  - ${REGISTRY}/frontend:${TAG}")"

git tag -a "$TAG" -m "$TAG_MESSAGE"
git push origin "$TAG"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  ✅ Deploy complete: ${TAG}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
kubectl get pods -n "$NAMESPACE"
