#!/bin/bash

# CloudXM Plugin Server Test Script
# Tests all scenarios: upload, latest.json generation, download, checksum validation

# set -e  # Temporarily disabled for debugging

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Configuration
SERVER_URL="http://localhost:8080"
AUTH_TOKEN="test-auth-token-12345"
TEST_PLUGIN_NAME="woocommerce-cloudxm-marlim"
TEST_VERSION="2.3.7"
TEST_ZIP_FILE="/test-data/woocommerce-cloudxm-marlim-v$TEST_VERSION.zip"

# Logging functions
log() {
    echo -e "${GREEN}✓ $1${NC}"
}

warn() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}"
}

info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

# Wait for server to be ready
wait_for_server() {
    info "Waiting for server to be ready..."
    for i in {1..30}; do
        if curl -s -f "$SERVER_URL/health" > /dev/null 2>&1; then
            log "Server is ready"
            return 0
        fi
        sleep 1
    done
    error "Server failed to start"
    exit 1
}

# Test health check endpoint
test_health_check() {
    info "Testing health check endpoint..."
    response=$(curl -s "$SERVER_URL/health")

    # Check if response contains "healthy" status
    if echo "$response" | grep -q '"status": "healthy"'; then
        log "Health check passed"
        return 0
    else
        error "Health check failed: $response"
        return 1
    fi
}

# Test plugin catalog (may contain previously uploaded plugins)
test_empty_catalog() {
    info "Testing plugin catalog..."
    response=$(curl -s -L "$SERVER_URL/plugins/")

    if echo "$response" | grep -q 'plugins'; then
        log "Plugin catalog test passed"
        return 0
    else
        error "Plugin catalog test failed: $response"
        return 1
    fi
}

# Test plugin upload with authentication
test_plugin_upload() {
    info "Testing plugin upload with authentication..."

    if [ ! -f "$TEST_ZIP_FILE" ]; then
        error "Test ZIP file not found: $TEST_ZIP_FILE"
        return 1
    fi

    response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "X-CloudXM-Auth: $AUTH_TOKEN" \
        -F "plugin=@$TEST_ZIP_FILE" \
        -F "plugin_name=$TEST_PLUGIN_NAME" \
        -F "version=$TEST_VERSION" \
        "$SERVER_URL/plugins/upload/")

    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | sed '$d')

    if [ "$http_code" -eq 200 ] && [[ "$response_body" == *'"success":true'* ]]; then
        log "Plugin upload successful"
        return 0
    else
        error "Plugin upload failed (HTTP $http_code): $response_body"
        return 1
    fi
}

# Test plugin upload without authentication (should fail)
test_unauthorized_upload() {
    info "Testing unauthorized upload (should fail)..."

    response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -F "plugin=@$TEST_ZIP_FILE" \
        -F "plugin_name=$TEST_PLUGIN_NAME" \
        -F "version=$TEST_VERSION" \
        "$SERVER_URL/plugins/upload")

    http_code=$(echo "$response" | tail -n1)

    if [ "$http_code" -eq 401 ]; then
        log "Unauthorized upload correctly rejected"
        return 0
    else
        error "Unauthorized upload should have been rejected (got HTTP $http_code)"
        return 1
    fi
}

# Test latest.json generation
test_latest_json_generation() {
    info "Testing latest.json generation..."

    response=$(curl -s "$SERVER_URL/woocommerce-$TEST_PLUGIN_NAME/latest.json")

    if [[ "$response" == *'"version":"2.3.7"'* ]] && [[ "$response" == *'"name"'* ]]; then
        log "latest.json generation successful"

        # Extract and save checksum
        echo "$response" | grep -o '"download_url":"[^"]*"' | cut -d'"' -f4 | xargs basename > /tmp/test_checksum.txt
        return 0
    else
        error "latest.json generation failed: $response"
        return 1
    fi
}

# Test plugin download
test_plugin_download() {
    info "Testing plugin download..."

    response=$(curl -s -w "\n%{http_code}" \
        -o /tmp/downloaded_plugin.zip \
        "$SERVER_URL/woocommerce-$TEST_PLUGIN_NAME/woocommerce-cloudxm-marlim-v$TEST_VERSION.zip")

    http_code=$(echo "$response" | tail -n1)

    if [ "$http_code" -eq 200 ] && [ -f /tmp/downloaded_plugin.zip ]; then
        log "Plugin download successful"
        return 0
    else
        error "Plugin download failed (HTTP $http_code)"
        return 1
    fi
}

# Test checksum validation
test_checksum_validation() {
    info "Testing checksum validation..."

    if [ ! -f "$TEST_ZIP_FILE" ] || [ ! -f /tmp/downloaded_plugin.zip ]; then
        error "Test files not available for checksum comparison"
        return 1
    fi

    original_checksum=$(sha256sum "$TEST_ZIP_FILE" | cut -d' ' -f1)
    downloaded_checksum=$(sha256sum /tmp/downloaded_plugin.zip | cut -d' ' -f1)

    if [ "$original_checksum" = "$downloaded_checksum" ]; then
        log "Checksum validation passed"
        return 0
    else
        error "Checksum validation failed - files differ"
        return 1
    fi
}

# Test plugin catalog after upload
test_updated_catalog() {
    info "Testing updated plugin catalog..."

    response=$(curl -s -L "$SERVER_URL/plugins/")

    if [[ "$response" == *"$TEST_PLUGIN_NAME"* ]] && [[ "$response" == *'"currentVersion":"2.3.7"'* ]]; then
        log "Updated catalog test passed"
        return 0
    else
        error "Updated catalog test failed: $response"
        return 1
    fi
}

# Test catalog update endpoint
test_catalog_update() {
    info "Testing catalog update endpoint..."

    response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "Content-Type: application/json" \
        -H "X-CloudXM-Auth: $AUTH_TOKEN" \
        -d "{
            \"plugins\": {
                \"$TEST_PLUGIN_NAME\": {
                    \"name\": \"CloudXM Marlim Gateway\",
                    \"description\": \"Payment gateway for WooCommerce\",
                    \"currentVersion\": \"$TEST_VERSION\",
                    \"downloadUrl\": \"$SERVER_URL/woocommerce-$TEST_PLUGIN_NAME/woocommerce-cloudxm-marlim-v$TEST_VERSION.zip\",
                    \"distributionUrl\": \"$SERVER_URL/woocommerce-$TEST_PLUGIN_NAME/\",
                    \"infoUrl\": \"$SERVER_URL/woocommerce-$TEST_PLUGIN_NAME/latest.json\"
                }
            },
            \"environment\": \"test\",
            \"baseUrl\": \"$SERVER_URL\"
        }" \
        "$SERVER_URL/plugins/catalog")

    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | sed '$d')

    if [ "$http_code" -eq 200 ] && [[ "$response_body" == *'"success":true'* ]]; then
        log "Catalog update successful"
        return 0
    else
        error "Catalog update failed (HTTP $http_code): $response_body"
        return 1
    fi
}

# Test HTML interface
test_html_interface() {
    info "Testing HTML interface..."

    response=$(curl -s -H "Accept: text/html" "$SERVER_URL/")

    if [[ "$response" == *"CloudXM Plugins"* ]] && [[ "$response" == *"Loading plugin catalog"* ]]; then
        log "HTML interface test passed"
        return 0
    else
        error "HTML interface test failed"
        return 1
    fi
}

# Test environment detection
test_environment_detection() {
    info "Testing environment detection..."

    # Test stable environment
    response=$(curl -s "$SERVER_URL/stable/plugins")
    if [[ "$response" == *'"environment":"stable"'* ]]; then
        log "Stable environment detection passed"
    else
        error "Stable environment detection failed"
        return 1
    fi

    # Test dev environment
    response=$(curl -s "$SERVER_URL/dev/plugins")
    if [[ "$response" == *'"environment":"dev"'* ]]; then
        log "Dev environment detection passed"
        return 0
    else
        error "Dev environment detection failed"
        return 1
    fi
}

# Main test function
main() {
    echo -e "${BLUE}🚀 Starting CloudXM Plugin Server Tests${NC}"
    echo

    # Setup
    wait_for_server

    # Run all tests
    tests=(
        "test_health_check"
        "test_empty_catalog"
        "test_unauthorized_upload"
        "test_plugin_upload"
        "test_latest_json_generation"
        "test_plugin_download"
        "test_checksum_validation"
        "test_updated_catalog"
        "test_catalog_update"
        "test_html_interface"
        "test_environment_detection"
    )

    passed=0
    failed=0

    for test_func in "${tests[@]}"; do
        echo
        if $test_func; then
            ((passed++))
        else
            ((failed++))
        fi
    done

    echo
    echo -e "${BLUE}📊 Test Results:${NC}"
    echo "Passed: $passed"
    echo "Failed: $failed"
    echo "Total: $((passed + failed))"

    if [ $failed -eq 0 ]; then
        echo -e "${GREEN}🎉 All tests passed!${NC}"
        exit 0
    else
        echo -e "${RED}💥 $failed test(s) failed${NC}"
        exit 1
    fi
}

# Run main function
main "$@"