#!/bin/bash
# Deployment notification script using Resend API
# Sends email notifications for deployment events
#
# Usage: ./notify.sh <event_type> [message] [commit_sha]
#   event_type: success, failure, rollback, rollback_failed, maintenance_start, maintenance_end, staging_ready
#   message: Optional custom message
#   commit_sha: Optional commit SHA for context
#
# Required environment variables:
#   DEPLOY_NOTIFY_EMAIL - Recipient email address
#
# Reads Resend API key from:
#   /run/secrets/resend-api-key (container)
#   ./secrets/app/resend-api-key.txt (local)
#
# Exit codes:
#   0 - Notification sent (or skipped if not configured)
#   1 - Notification failed

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

EVENT_TYPE="${1:-}"
MESSAGE="${2:-}"
COMMIT_SHA="${3:-${CI_COMMIT_SHORT_SHA:-unknown}}"

if [[ -z "$EVENT_TYPE" ]]; then
  echo "Usage: $0 <success|failure|rollback|rollback_failed|maintenance_start|maintenance_end> [message] [commit_sha]"
  exit 1
fi

# Get recipient email
NOTIFY_EMAIL="${DEPLOY_NOTIFY_EMAIL:-}"
if [[ -z "$NOTIFY_EMAIL" ]]; then
  echo "DEPLOY_NOTIFY_EMAIL not set, skipping notification"
  exit 0
fi

# Get Resend API key (check env first for Gitea, then files for containers)
if [[ -z "${RESEND_API_KEY:-}" ]]; then
  if [[ -f "/run/secrets/resend-api-key" ]]; then
    RESEND_API_KEY=$(cat /run/secrets/resend-api-key)
  elif [[ -f "$PROJECT_ROOT/secrets/app/resend-api-key.txt" ]]; then
    RESEND_API_KEY=$(cat "$PROJECT_ROOT/secrets/app/resend-api-key.txt")
  fi
fi

if [[ -z "${RESEND_API_KEY:-}" ]]; then
  echo "WARNING: Resend API key not found, skipping notification"
  exit 0
fi

# Determine subject and styling based on event type
case "$EVENT_TYPE" in
  "success")
    SUBJECT="Deployment Successful - MotoVaultPro"
    STATUS_COLOR="#22c55e"
    STATUS_EMOJI="[OK]"
    STATUS_TEXT="Deployment Successful"
    DEFAULT_MESSAGE="Version $COMMIT_SHA is now live."
    ;;
  "failure")
    SUBJECT="Deployment Failed - MotoVaultPro"
    STATUS_COLOR="#ef4444"
    STATUS_EMOJI="[FAILED]"
    STATUS_TEXT="Deployment Failed"
    DEFAULT_MESSAGE="Deployment of $COMMIT_SHA failed. Check pipeline logs."
    ;;
  "rollback")
    SUBJECT="Auto-Rollback Executed - MotoVaultPro"
    STATUS_COLOR="#f59e0b"
    STATUS_EMOJI="[ROLLBACK]"
    STATUS_TEXT="Rollback Executed"
    DEFAULT_MESSAGE="Automatic rollback was triggered. Previous version restored."
    ;;
  "rollback_failed")
    SUBJECT="CRITICAL: Rollback Failed - MotoVaultPro"
    STATUS_COLOR="#dc2626"
    STATUS_EMOJI="[CRITICAL]"
    STATUS_TEXT="Rollback Failed"
    DEFAULT_MESSAGE="Rollback attempt failed. Manual intervention required immediately."
    ;;
  "maintenance_start")
    SUBJECT="Maintenance Mode Started - MotoVaultPro"
    STATUS_COLOR="#6366f1"
    STATUS_EMOJI="[MAINTENANCE]"
    STATUS_TEXT="Maintenance Mode Active"
    DEFAULT_MESSAGE="Application is in maintenance mode for database migration."
    ;;
  "maintenance_end")
    SUBJECT="Maintenance Mode Ended - MotoVaultPro"
    STATUS_COLOR="#22c55e"
    STATUS_EMOJI="[ONLINE]"
    STATUS_TEXT="Maintenance Complete"
    DEFAULT_MESSAGE="Maintenance window complete. Application is online."
    ;;
  "staging_ready")
    SUBJECT="Staging Ready for Production - MotoVaultPro"
    STATUS_COLOR="#3b82f6"
    STATUS_EMOJI="[STAGING]"
    STATUS_TEXT="Staging Verified"
    DEFAULT_MESSAGE="Staging deployment verified. Ready for production deployment."
    ;;
  *)
    echo "Unknown event type: $EVENT_TYPE"
    exit 1
    ;;
esac

# Use custom message or default
FINAL_MESSAGE="${MESSAGE:-$DEFAULT_MESSAGE}"
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")

# Build HTML email
HTML_BODY=$(cat <<EOF
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f3f4f6; padding: 20px; }
    .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .header { background: ${STATUS_COLOR}; color: white; padding: 20px; text-align: center; }
    .header h1 { margin: 0; font-size: 24px; }
    .content { padding: 30px; }
    .status { font-size: 18px; font-weight: 600; margin-bottom: 15px; }
    .message { color: #374151; line-height: 1.6; margin-bottom: 20px; }
    .details { background: #f9fafb; border-radius: 6px; padding: 15px; font-size: 14px; }
    .details-row { display: flex; justify-content: space-between; margin-bottom: 8px; }
    .details-label { color: #6b7280; }
    .details-value { color: #111827; font-weight: 500; }
    .footer { padding: 20px; text-align: center; color: #6b7280; font-size: 12px; border-top: 1px solid #e5e7eb; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>MotoVaultPro</h1>
    </div>
    <div class="content">
      <div class="status">${STATUS_EMOJI} ${STATUS_TEXT}</div>
      <div class="message">${FINAL_MESSAGE}</div>
      <div class="details">
        <div class="details-row">
          <span class="details-label">Environment:</span>
          <span class="details-value">Production</span>
        </div>
        <div class="details-row">
          <span class="details-label">Commit:</span>
          <span class="details-value">${COMMIT_SHA}</span>
        </div>
        <div class="details-row">
          <span class="details-label">Time:</span>
          <span class="details-value">${TIMESTAMP}</span>
        </div>
      </div>
    </div>
    <div class="footer">
      MotoVaultPro CI/CD Notification System
    </div>
  </div>
</body>
</html>
EOF
)

# Send email via Resend API
echo "Sending notification: $EVENT_TYPE"
echo "  To: $NOTIFY_EMAIL"
echo "  Subject: $SUBJECT"

# Build JSON payload
JSON_PAYLOAD=$(cat <<EOF
{
  "from": "MotoVaultPro <deploy@motovaultpro.com>",
  "to": ["$NOTIFY_EMAIL"],
  "subject": "$SUBJECT",
  "html": $(echo "$HTML_BODY" | jq -Rs .)
}
EOF
)

# Send via Resend API
RESPONSE=$(curl -s -w "\n%{http_code}" \
  -X POST \
  -H "Authorization: Bearer $RESEND_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$JSON_PAYLOAD" \
  "https://api.resend.com/emails")

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | sed '$d')

if [[ "$HTTP_CODE" == "200" ]] || [[ "$HTTP_CODE" == "201" ]]; then
  echo "  OK: Notification sent successfully"
  exit 0
else
  echo "  ERROR: Failed to send notification (HTTP $HTTP_CODE)"
  echo "  Response: $BODY"
  exit 1
fi
