#!/bin/bash

# Unified CloudXM Plugin Build/Deploy Notification System
# Handles both Build and Deploy phases with clear messaging
# Usage: ./unified-notification.sh <phase> <status> [error_message]
#
# Parameters:
#   phase: 'build' or 'deploy'
#   status: 'success' or 'failure'
#   error_message: Optional error details for failures

set -e

# Source the telegram notification script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/notify-telegram.sh" 2>/dev/null || true

# Function to extract plugin version from plugin file
get_plugin_version() {
    local plugin_file="$1"
    if [ -f "$plugin_file" ]; then
        # Try to get version from plugin header
        local version=$(grep "Version:" "$plugin_file" | head -1 | sed 's/.*Version:\s*//' | tr -d '\r' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
        # If version is empty, try alternative patterns
        if [ -z "$version" ]; then
            version=$(grep -i "version" "$plugin_file" | grep -E "const|define" | head -1 | sed 's/.*["'\'']//' | sed 's/["'\''];.*//' | tr -d '\r' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
        fi
        # Fallback to latest.json if available
        if [ -z "$version" ] && [ -f "latest.json" ]; then
            version=$(jq -r .version latest.json 2>/dev/null || echo "")
        fi
        echo "${version:-unknown}"
    else
        echo "unknown"
    fi
}

# Function to extract plugin name from plugin file
get_plugin_name() {
    local plugin_file="$1"

    # If PLUGIN_NAME environment variable is set, use it
    if [ -n "$PLUGIN_NAME" ]; then
        echo "$PLUGIN_NAME"
    elif [ -f "$plugin_file" ]; then
        basename "$plugin_file" .php
    else
        echo "woocommerce-cloudxm-envioz"
    fi
}

# Function to get plugin information
get_plugin_info() {
    local plugin_count=0
    local plugin_list=""

    for plugin_dir in plugins/*/; do
        if [ -d "$plugin_dir" ] && [ -f "$plugin_dir/latest.json" ]; then
            plugin_name=$(basename "$plugin_dir")
            version=$(jq -r .version "$plugin_dir/latest.json" 2>/dev/null || echo "unknown")

            plugin_list="$plugin_list• $plugin_name v$version\n"
            plugin_count=$((plugin_count + 1))
        fi
    done

    echo "$plugin_count|$plugin_list"
}

# Function to send build success notification
notify_build_success() {
    local plugin_file="$1"
    local plugin_name=$(get_plugin_name "$plugin_file")
    local version=$(get_plugin_version "$plugin_file")

    local message=""
    if [ "$PLUGIN_COUNT" -gt 0 ]; then
        message="Build completed successfully!

*Plugins Built:* $PLUGIN_COUNT
$PLUGIN_LIST
*Build Duration:* ${CI_JOB_DURATION:-unknown}s"
    else
        message="Build completed successfully!

*Plugin Built:* $plugin_name v$version
*Archive:* public/$plugin_name-$version.zip
*Build Duration:* ${CI_JOB_DURATION:-unknown}s"
    fi

    send_notification "✅ *CloudXM Plugin Build SUCCESS*" "$message"
}

# Function to send build failure notification
notify_build_failure() {
    local plugin_file="$1"
    local error_message="${1:-Build failed with unknown error}"
    local plugin_name=$(get_plugin_name "$plugin_file")

    local message="Build failed!

*Plugin:* $plugin_name
*Error:* $error_message
*Build Duration:* ${CI_JOB_DURATION:-unknown}s"

    send_notification "❌ *CloudXM Plugin Build FAILED*" "$message"
}

# Function to send deploy success notification
notify_deploy_success() {
    local plugin_file="$1"
    local plugin_name=$(get_plugin_name "$plugin_file")
    local version=$(get_plugin_version "$plugin_file")
    local deploy_url="$2"

    local message="Plugin deployed successfully!

*Plugin:* $plugin_name v$version
*Environment:* $([ -n "$CI_COMMIT_TAG" ] && echo "🚀 Production" || echo "🔧 Development")
*Deploy URL:* $deploy_url"

    send_notification "🚀 *CloudXM Plugin Deploy SUCCESS*" "$message"
}

# Function to send deploy failure notification
notify_deploy_failure() {
    local plugin_file="$1"
    local error_message="${1:-Deploy failed with unknown error}"
    local plugin_name=$(get_plugin_name "$plugin_file")

    local message="Plugin deployment failed!

*Plugin:* $plugin_name
*Error:* $error_message
*Environment:* $([ -n "$CI_COMMIT_TAG" ] && echo "🚀 Production" || echo "🔧 Development")"

    send_notification "💥 *CloudXM Plugin Deploy FAILED*" "$message"
}

# Unified notification sender
send_notification() {
    local title="$1"
    local message="$2"

    if command -v send_telegram_notification >/dev/null 2>&1; then
        NOTIFICATION="$title

*Environment:* $([ -n "$CI_COMMIT_TAG" ] && echo "🚀 Production" || echo "🔧 Development")
*Branch/Tag:* \`${CI_COMMIT_REF_NAME:-unknown}\`
*Commit:* \`${CI_COMMIT_SHORT_SHA:-unknown}\`
*Pipeline:* [#${CI_PIPELINE_ID:-unknown}](${CI_PIPELINE_URL:-#})

$message

*Website:* https://plugin.cloudxm.com.br

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

        send_telegram_notification
    else
        echo "📱 Telegram notification function not available"
        echo "$title"
        echo "$message"
    fi
}

# Main execution
PHASE="$1"
STATUS="$2"
PLUGIN_FILE="$3"
EXTRA_INFO="$4"

# Get plugin info for multi-plugin builds
PLUGIN_INFO=$(get_plugin_info)
PLUGIN_COUNT=$(echo "$PLUGIN_INFO" | cut -d'|' -f1)
PLUGIN_LIST=$(echo "$PLUGIN_INFO" | cut -d'|' -f2)

case "${PHASE:-build}" in
    "build")
        case "${STATUS:-success}" in
            "success")
                notify_build_success "$PLUGIN_FILE"
                ;;
            "failure")
                notify_build_failure "$PLUGIN_FILE" "$EXTRA_INFO"
                ;;
            *)
                echo "Usage: $0 build [success|failure] [plugin_file] [error_message]"
                exit 1
                ;;
        esac
        ;;
    "deploy")
        case "${STATUS:-success}" in
            "success")
                notify_deploy_success "$PLUGIN_FILE" "$EXTRA_INFO"
                ;;
            "failure")
                notify_deploy_failure "$PLUGIN_FILE" "$EXTRA_INFO"
                ;;
            *)
                echo "Usage: $0 deploy [success|failure] [plugin_file] [error_message/deploy_url]"
                exit 1
                ;;
        esac
        ;;
    *)
        echo "Usage: $0 <phase> <status> [plugin_file] [extra_info]"
        echo "Phases: build, deploy"
        echo "Status: success, failure"
        exit 1
        ;;
esac