#!/bin/bash
# Post-deploy hook - triggers approval card capture after deployments
# Usage: post-deploy-hook.sh <slug> <type> <changes...>
#
# Types:
#   landing - Landing page at *.landing.symph.co
#   app     - Dev app at *.dev.apps.symph.co
#
# This runs async (fire-and-forget) so it doesn't block deploys.

set -e

SLUG="$1"
TYPE="$2"
shift 2
CHANGES=("$@")

if [ -z "$SLUG" ] || [ -z "$TYPE" ]; then
  echo "[PostDeploy] Usage: post-deploy-hook.sh <slug> <type> <changes...>"
  exit 1
fi

# Default changes if none provided - try to extract from recent git commits
if [ ${#CHANGES[@]} -eq 0 ]; then
  # Check if we're in a git repo and try to get recent commit messages
  PROJECT_DIR=""
  if [ "$TYPE" = "landing" ]; then
    PROJECT_DIR="/home/aria/projects/${SLUG}-landing"
  else
    PROJECT_DIR="/home/aria/products/${SLUG}/apps/main"
  fi
  
  if [ -d "$PROJECT_DIR/.git" ] || [ -d "$PROJECT_DIR/../.git" ]; then
    cd "$PROJECT_DIR" 2>/dev/null || cd "$(dirname "$PROJECT_DIR")" 2>/dev/null
    # Get last 3 commit messages (excluding merge commits)
    RECENT_COMMITS=$(git log --oneline --no-merges -3 2>/dev/null | cut -d' ' -f2- || echo "")
    if [ -n "$RECENT_COMMITS" ]; then
      while IFS= read -r line; do
        [ -n "$line" ] && CHANGES+=("$line")
      done <<< "$RECENT_COMMITS"
    fi
  fi
  
  # Still empty? Use generic message
  if [ ${#CHANGES[@]} -eq 0 ]; then
    CHANGES=("Code changes deployed")
  fi
fi

# Build JSON array of changes
CHANGES_JSON="["
first=true
for change in "${CHANGES[@]}"; do
  if [ "$first" = true ]; then
    first=false
  else
    CHANGES_JSON+=","
  fi
  # Escape quotes in change text
  escaped=$(echo "$change" | sed 's/"/\\"/g')
  CHANGES_JSON+="\"$escaped\""
done
CHANGES_JSON+="]"

# Symphony API endpoint
API_URL="${SYMPHONY_API_URL:-http://localhost:4000}/api/approval/capture"

echo "[PostDeploy] Triggering approval capture for $SLUG ($TYPE)"

# Fire-and-forget async request
(
  sleep 5  # Wait for app to fully start
  curl -s -X POST "$API_URL" \
    -H "Content-Type: application/json" \
    -d "{
      \"productSlug\": \"$SLUG\",
      \"type\": \"$TYPE\",
      \"changes\": $CHANGES_JSON,
      \"triggeredBy\": \"deploy-hook\"
    }" > /tmp/approval-capture-$SLUG.log 2>&1
  echo "[PostDeploy] Capture triggered for $SLUG - check /tmp/approval-capture-$SLUG.log"
) &

disown
echo "[PostDeploy] Async capture started"
