#!/bin/bash
# Test script for THREESCALE-11214
# Tests that provider creation via Master API doesn't trigger TenantLeak errors
# even under concurrent load conditions that might cause database deadlocks

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration - use environment variables with defaults
NUM_REQUESTS=${NUM_REQUESTS:-50}
CONCURRENT_BATCH=${CONCURRENT_BATCH:-10}

# Check required environment variables
if [ -z "$MASTER_TOKEN" ]; then
    echo -e "${RED}ERROR: MASTER_TOKEN environment variable is not set${NC}"
    echo "Please set it with: export MASTER_TOKEN=your_master_api_key"
    exit 1
fi

if [ -z "$MASTER_HOST" ]; then
    echo -e "${RED}ERROR: MASTER_HOST environment variable is not set${NC}"
    echo "Please set it with: export MASTER_HOST=master.3scale.localhost"
    exit 1
fi

# Determine BASE_URL - handle if MASTER_HOST already has http:// or https://
if [[ "$MASTER_HOST" == http://* || "$MASTER_HOST" == https://* ]]; then
    BASE_URL="${MASTER_HOST}"
elif [[ "$MASTER_HOST" == *":"* ]]; then
    BASE_URL="http://${MASTER_HOST}"
else
    BASE_URL="http://${MASTER_HOST}:3000"
fi


ENDPOINT="${BASE_URL}/master/api/providers.json"

echo -e "${GREEN}=== THREESCALE-11214 Test Script ===${NC}"
echo "Testing provider creation under concurrent load"
echo "Endpoint: $ENDPOINT"
echo "Number of requests: $NUM_REQUESTS"
echo "Concurrent batch size: $CONCURRENT_BATCH"
echo ""

# Create temp directory for results
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

SUCCESS_COUNT=0
FAILURE_COUNT=0
TENANT_LEAK_COUNT=0

# Function to send a single request
send_request() {
    local i=$1
    local output_file="${TEMP_DIR}/response_${i}.txt"
    local status_file="${TEMP_DIR}/status_${i}.txt"

    # Use unique values for each request
    local org_name="TestOrg${i}"
    local username="testuser${i}"
    local email="test${i}@example.com"
    local password="p"

    # Send request and capture HTTP status code
    # Use -k to allow insecure SSL connections for test/dev environments
    http_code=$(curl -s -k -w "%{http_code}" -o "$output_file" \
        -X POST "$ENDPOINT" \
        -d "access_token=${MASTER_TOKEN}" \
        -d "org_name=${org_name}" \
        -d "username=${username}" \
        -d "email=${email}" \
        -d "password=${password}" \
        2>&1)

    echo "$http_code" > "$status_file"

    # Check for TenantLeak in response
    if grep -q "TenantLeak" "$output_file" 2>/dev/null; then
        echo "TENANT_LEAK" >> "${TEMP_DIR}/tenant_leak_errors.txt"
        echo -e "${RED}[${i}] TENANT_LEAK ERROR detected!${NC}"
    fi
}

export -f send_request
export ENDPOINT MASTER_TOKEN TEMP_DIR RED GREEN NC

echo -e "${YELLOW}Starting concurrent requests...${NC}"
echo ""

# Check if GNU parallel is available
if command -v parallel &> /dev/null; then
    echo "Using GNU parallel for concurrent requests"
    seq 1 $NUM_REQUESTS | parallel -j $CONCURRENT_BATCH send_request {}
else
    echo "Using background jobs for concurrent requests (consider installing 'parallel' for better performance)"

    # Send requests in batches
    for ((i=1; i<=NUM_REQUESTS; i++)); do
        send_request $i &

        # Wait for batch to complete before starting next batch
        if (( i % CONCURRENT_BATCH == 0 )); then
            wait
            TOTAL_BATCHES=$(( (NUM_REQUESTS + CONCURRENT_BATCH - 1) / CONCURRENT_BATCH ))
            echo -e "${YELLOW}Completed batch $(( i / CONCURRENT_BATCH ))/${TOTAL_BATCHES}${NC}"
        fi
    done

    # Wait for remaining jobs
    wait
fi

echo ""
echo -e "${YELLOW}All requests completed. Analyzing results...${NC}"
echo ""

# Analyze results
for ((i=1; i<=NUM_REQUESTS; i++)); do
    status_file="${TEMP_DIR}/status_${i}.txt"
    response_file="${TEMP_DIR}/response_${i}.txt"

    if [ -f "$status_file" ]; then
        http_code=$(cat "$status_file")

        # Check for success (201 Created or 200 OK)
        if [[ "$http_code" == "201" || "$http_code" == "200" ]]; then
            ((SUCCESS_COUNT++))
        else
            ((FAILURE_COUNT++))

            # Check if failure is due to TenantLeak
            if grep -q "TenantLeak" "$response_file" 2>/dev/null; then
                ((TENANT_LEAK_COUNT++))
                echo -e "${RED}Request ${i}: HTTP ${http_code} - TENANT_LEAK ERROR${NC}"
            else
                # Show first few non-TenantLeak errors for debugging
                if [ $FAILURE_COUNT -le 5 ]; then
                    echo -e "${YELLOW}Request ${i}: HTTP ${http_code}${NC}"
                    if [ -f "$response_file" ]; then
                        head -n 3 "$response_file" | sed 's/^/  /'
                    fi
                fi
            fi
        fi
    fi
done

echo ""
echo -e "${GREEN}=== Test Results ===${NC}"
echo "Total requests: $NUM_REQUESTS"
echo -e "Successful (201/200): ${GREEN}${SUCCESS_COUNT}${NC}"
echo -e "Failed (non-201/200): ${YELLOW}${FAILURE_COUNT}${NC}"
echo -e "TenantLeak errors: ${RED}${TENANT_LEAK_COUNT}${NC}"
echo ""

# Final verdict
if [ $TENANT_LEAK_COUNT -eq 0 ]; then
    echo -e "${GREEN}✓ TEST PASSED: No TenantLeak errors detected!${NC}"
    echo -e "${GREEN}The fix for THREESCALE-11214 is working correctly.${NC}"
    exit 0
else
    echo -e "${RED}✗ TEST FAILED: ${TENANT_LEAK_COUNT} TenantLeak error(s) detected!${NC}"
    echo -e "${RED}The fix for THREESCALE-11214 may not be working correctly.${NC}"
    echo ""
    echo "TenantLeak errors found in:"
    if [ -f "${TEMP_DIR}/tenant_leak_errors.txt" ]; then
        wc -l < "${TEMP_DIR}/tenant_leak_errors.txt"
        echo "requests"
    fi
    exit 1
fi