#!/bin/bash
# ============================================================================
# Functional Test: Tenant Deletion System (Simple Version)
# ============================================================================

set +e  # Don't exit on error

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

# Configuration
TENANT_ID="${1:-dbc2128a-7539-470c-94b9-c1e37031bd77}"

# Generate or use provided SERVICE_TOKEN
if [ -z "${SERVICE_TOKEN}" ]; then
    SERVICE_TOKEN=$(python3 scripts/generate_service_token.py tenant-deletion-orchestrator 2>&1 | grep -A1 "Token:" | tail -1 | sed 's/^[[:space:]]*//' | tr -d '\n')
else
    # Clean the token if provided (remove whitespace and newlines)
    SERVICE_TOKEN=$(echo "${SERVICE_TOKEN}" | tr -d '[:space:]')
fi

# Results
TOTAL_SERVICES=12
SUCCESSFUL_TESTS=0
FAILED_TESTS=0

# Helper functions
print_header() {
    echo -e "${BLUE}================================================================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}================================================================================${NC}"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

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

# Test function
test_service() {
    local service_name=$1
    local endpoint_path=$2
    local port=${3:-8000}  # Default to 8000 if not specified

    echo ""
    echo -e "${BLUE}Testing ${service_name}...${NC}"

    # Find running pod
    local pod=$(kubectl get pods -n bakery-ia 2>/dev/null | grep "${service_name}" | grep "Running" | grep "1/1" | head -1 | awk '{print $1}')

    if [ -z "$pod" ]; then
        print_error "No running pod found"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi

    print_info "Pod: ${pod}"

    # Execute request
    local result=$(kubectl exec -n bakery-ia "$pod" -- curl -s -w "\nHTTP_CODE:%{http_code}" \
        -H "Authorization: Bearer ${SERVICE_TOKEN}" \
        "http://localhost:${port}${endpoint_path}/tenant/${TENANT_ID}/deletion-preview" 2>&1)

    local http_code=$(echo "$result" | grep "HTTP_CODE" | cut -d':' -f2)
    local body=$(echo "$result" | sed '/HTTP_CODE/d')

    if [ "$http_code" = "200" ]; then
        print_success "Preview successful (HTTP ${http_code})"
        local total=$(echo "$body" | grep -o '"total_records":[0-9]*' | cut -d':' -f2 | head -1)
        if [ -n "$total" ]; then
            print_info "Records to delete: ${total}"
        fi
        SUCCESSFUL_TESTS=$((SUCCESSFUL_TESTS + 1))
        return 0
    elif [ "$http_code" = "401" ]; then
        print_error "Authentication failed (HTTP ${http_code})"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    elif [ "$http_code" = "403" ]; then
        print_error "Authorization failed (HTTP ${http_code})"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    elif [ "$http_code" = "404" ]; then
        print_error "Endpoint not found (HTTP ${http_code})"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    elif [ "$http_code" = "500" ]; then
        print_error "Server error (HTTP ${http_code})"
        echo "$body" | head -3
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    else
        print_error "Unexpected response (HTTP ${http_code})"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
}

# Main
print_header "Tenant Deletion System - Functional Test"
echo ""
print_info "Tenant ID: ${TENANT_ID}"
print_info "Services to test: ${TOTAL_SERVICES}"
echo ""

# Test all services
test_service "orders-service" "/api/v1/orders"
test_service "inventory-service" "/api/v1/inventory"
test_service "recipes-service" "/api/v1/recipes"
test_service "sales-service" "/api/v1/sales"
test_service "production-service" "/api/v1/production"
test_service "suppliers-service" "/api/v1/suppliers"
test_service "pos-service" "/api/v1/pos"
test_service "external-service" "/api/v1/external"
test_service "forecasting-service" "/api/v1/forecasting"
test_service "training-service" "/api/v1/training"
test_service "alert-processor-api" "/api/v1/alerts" 8010
test_service "notification-service" "/api/v1/notification"

# Summary
echo ""
print_header "Test Results"
echo "Total Services: ${TOTAL_SERVICES}"
echo -e "${GREEN}Successful:${NC} ${SUCCESSFUL_TESTS}/${TOTAL_SERVICES}"
echo -e "${RED}Failed:${NC} ${FAILED_TESTS}/${TOTAL_SERVICES}"
echo ""

if [ ${FAILED_TESTS} -eq 0 ]; then
    print_success "All tests passed!"
    exit 0
else
    print_error "Some tests failed"
    exit 1
fi
