#!/bin/bash
# Example: post_merge hook
#
# This hook runs after a successful merge into the target branch.
# Use it to trigger deployments, close issues, notify teams, etc.

set -e

echo "[Hook] Post-merge processing for $DMUX_SLUG → $DMUX_TARGET_BRANCH"

cd "$DMUX_ROOT"

# Push to remote if merging to main/master
if [ "$DMUX_TARGET_BRANCH" = "main" ] || [ "$DMUX_TARGET_BRANCH" = "master" ]; then
  echo "[Hook] Pushing to origin/$DMUX_TARGET_BRANCH"
  git push origin "$DMUX_TARGET_BRANCH"

  # Optional: Trigger deployment
  # if [ -n "$VERCEL_TOKEN" ]; then
  #   echo "[Hook] Triggering Vercel deployment..."
  #   curl -X POST "https://api.vercel.com/v1/deployments" \
  #     -H "Authorization: Bearer $VERCEL_TOKEN" \
  #     -H "Content-Type: application/json" \
  #     -d '{
  #       "name": "my-project",
  #       "gitSource": {
  #         "type": "github",
  #         "ref": "main"
  #       }
  #     }'
  # fi
fi

# Close related GitHub issue (if prompt contains #123 format)
ISSUE_NUM=$(echo "$DMUX_PROMPT" | grep -oP '#\K\d+' | head -1)
if [ -n "$ISSUE_NUM" ]; then
  echo "[Hook] Closing GitHub issue #$ISSUE_NUM"
  if command -v gh &> /dev/null; then
    gh issue close "$ISSUE_NUM" \
      -c "Resolved in branch $DMUX_SLUG, merged to $DMUX_TARGET_BRANCH" \
      2>/dev/null || echo "[Hook] Warning: Failed to close issue (maybe already closed?)"
  else
    echo "[Hook] GitHub CLI (gh) not found, skipping issue close"
  fi
fi

# Send notification to Slack
# if [ -n "$SLACK_WEBHOOK" ]; then
#   echo "[Hook] Sending Slack notification"
#   curl -s -X POST "$SLACK_WEBHOOK" \
#     -H "Content-Type: application/json" \
#     -d "{
#       \"text\": \"Merged: $DMUX_SLUG → $DMUX_TARGET_BRANCH\",
#       \"blocks\": [
#         {
#           \"type\": \"section\",
#           \"text\": {
#             \"type\": \"mrkdwn\",
#             \"text\": \"*Branch Merged* :rocket:\n\n*From:* \`$DMUX_SLUG\`\n*To:* \`$DMUX_TARGET_BRANCH\`\n*Task:* $DMUX_PROMPT\"
#           }
#         }
#       ]
#     }" > /dev/null
# fi

echo "[Hook] Post-merge processing complete"
