#!/bin/bash

# Telegram notification script for build completion
# Usage: ./scripts/notify-telegram.sh [success|failure] [message]

set -e

# Telegram Bot Configuration
BOT_TOKEN="${TELEGRAM_BOT_TOKEN:-7550464519:AAF9pgayjIVqi3wOiv0sQv7HGnfgTYesCcE}" # Fallback to default if not set
CHAT_ID="${TELEGRAM_CHAT_ID:-}" # Set this as GitLab CI variable

# Function to send notification
send_telegram_notification() {
    # Check if required variables are set
    if [ -z "$CHAT_ID" ]; then
        echo "⚠️  TELEGRAM_CHAT_ID not set, skipping notification"
        return 0
    fi

    # Send notification to Telegram
    echo "📤 Sending Telegram notification..."

    RESPONSE=$(curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
        -H "Content-Type: application/json" \
        -d "{
            \"chat_id\": \"$CHAT_ID\",
            \"text\": \"$NOTIFICATION\"
        }")

    # Check if successful
    if echo "$RESPONSE" | grep -q '"ok":true'; then
        echo "📱 Telegram notification sent successfully"
    else
        echo "⚠️  Telegram notification failed"
        echo "Response: $RESPONSE" >&2
        return 1
    fi

    echo "✅ Notification script completed"
}

# Run directly if not sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    # Check if required variables are set
    if [ -z "$CHAT_ID" ]; then
        echo "⚠️  TELEGRAM_CHAT_ID not set, skipping notification"
        exit 0
    fi

    # Parse arguments
    STATUS="${1:-unknown}"
    MESSAGE="${2:-Build completed}"

    # Determine environment
    if [ -n "$CI_COMMIT_TAG" ]; then
        ENVIRONMENT="🚀 Production"
        ENV_URL="https://plugins.cloudxm.com.br"
    else
        ENVIRONMENT="🔧 Development"
        ENV_URL="https://dev-plugins.cloudxm.com.br"
    fi

    # Set emoji and color based on status
    case "$STATUS" in
        "success")
            EMOJI="✅"
            STATUS_TEXT="SUCCESS"
            ;;
        "failure")
            EMOJI="❌"
            STATUS_TEXT="FAILED"
            ;;
        *)
            EMOJI="ℹ️"
            STATUS_TEXT="INFO"
            ;;
    esac

    # Build notification message (simple format that works)
    NOTIFICATION="$EMOJI CloudXM Plugin Build $STATUS_TEXT

Environment: $ENVIRONMENT
Branch/Tag: ${CI_COMMIT_REF_NAME:-unknown}
Commit: ${CI_COMMIT_SHORT_SHA:-unknown}
Pipeline: #${CI_PIPELINE_ID:-unknown}

Message: $MESSAGE

Website: $ENV_URL

Time: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"

    # Send notification
    send_telegram_notification
fi