#!/bin/bash
# ================================================================
# Tenant Deletion System - Integration Test Script
# ================================================================
# Tests all 12 services' deletion endpoints
# Usage: ./scripts/test_deletion_system.sh [tenant_id]

set -e

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

# Configuration
TENANT_ID="${1:-dbc2128a-7539-470c-94b9-c1e37031bd77}"  # Default demo tenant
SERVICE_TOKEN="${SERVICE_TOKEN:-demo_service_token}"

# Service URLs (update these based on your environment)
ORDERS_URL="${ORDERS_URL:-http://localhost:8000/api/v1/orders}"
INVENTORY_URL="${INVENTORY_URL:-http://localhost:8001/api/v1/inventory}"
RECIPES_URL="${RECIPES_URL:-http://localhost:8002/api/v1/recipes}"
SALES_URL="${SALES_URL:-http://localhost:8003/api/v1/sales}"
PRODUCTION_URL="${PRODUCTION_URL:-http://localhost:8004/api/v1/production}"
SUPPLIERS_URL="${SUPPLIERS_URL:-http://localhost:8005/api/v1/suppliers}"
POS_URL="${POS_URL:-http://localhost:8006/api/v1/pos}"
EXTERNAL_URL="${EXTERNAL_URL:-http://localhost:8007/api/v1/external}"
FORECASTING_URL="${FORECASTING_URL:-http://localhost:8008/api/v1/forecasting}"
TRAINING_URL="${TRAINING_URL:-http://localhost:8009/api/v1/training}"
ALERT_PROCESSOR_URL="${ALERT_PROCESSOR_URL:-http://localhost:8010/api/v1/alerts}"
NOTIFICATION_URL="${NOTIFICATION_URL:-http://localhost:8011/api/v1/notifications}"

# Test results
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0
declare -a FAILED_SERVICES

# 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_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

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

# Test individual service deletion preview
test_service_preview() {
    local service_name=$1
    local service_url=$2
    local endpoint_path=$3

    TOTAL_TESTS=$((TOTAL_TESTS + 1))

    echo ""
    print_info "Testing $service_name service..."

    local full_url="${service_url}${endpoint_path}/tenant/${TENANT_ID}/deletion-preview"

    # Make request
    response=$(curl -k -s -w "\nHTTP_STATUS:%{http_code}" \
        -H "Authorization: Bearer ${SERVICE_TOKEN}" \
        -H "X-Service-Token: ${SERVICE_TOKEN}" \
        "${full_url}" 2>&1)

    # Extract HTTP status
    http_status=$(echo "$response" | grep "HTTP_STATUS" | cut -d':' -f2)
    body=$(echo "$response" | sed '/HTTP_STATUS/d')

    if [ "$http_status" = "200" ]; then
        # Parse total records if available
        total_records=$(echo "$body" | grep -o '"total_records":[0-9]*' | cut -d':' -f2 || echo "N/A")

        print_success "$service_name: HTTP $http_status (Records: $total_records)"
        PASSED_TESTS=$((PASSED_TESTS + 1))

        # Show preview details if verbose
        if [ "${VERBOSE:-0}" = "1" ]; then
            echo "$body" | jq '.' 2>/dev/null || echo "$body"
        fi
    else
        print_error "$service_name: HTTP $http_status"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        FAILED_SERVICES+=("$service_name")

        # Show error details
        echo "  URL: $full_url"
        echo "  Response: $body" | head -n 5
    fi
}

# Main test execution
main() {
    print_header "Tenant Deletion System - Integration Tests"
    print_info "Testing tenant: $TENANT_ID"
    print_info "Using service token: ${SERVICE_TOKEN:0:20}..."
    echo ""

    # Test all services
    print_header "Testing Individual Services (12 total)"

    test_service_preview "Orders" "$ORDERS_URL" "/orders"
    test_service_preview "Inventory" "$INVENTORY_URL" "/inventory"
    test_service_preview "Recipes" "$RECIPES_URL" "/recipes"
    test_service_preview "Sales" "$SALES_URL" "/sales"
    test_service_preview "Production" "$PRODUCTION_URL" "/production"
    test_service_preview "Suppliers" "$SUPPLIERS_URL" "/suppliers"
    test_service_preview "POS" "$POS_URL" "/pos"
    test_service_preview "External" "$EXTERNAL_URL" "/external"
    test_service_preview "Forecasting" "$FORECASTING_URL" "/forecasting"
    test_service_preview "Training" "$TRAINING_URL" "/training"
    test_service_preview "Alert Processor" "$ALERT_PROCESSOR_URL" "/alerts"
    test_service_preview "Notification" "$NOTIFICATION_URL" "/notifications"

    # Print summary
    echo ""
    print_header "Test Summary"
    echo -e "Total Tests:  $TOTAL_TESTS"
    echo -e "${GREEN}Passed:       $PASSED_TESTS${NC}"

    if [ $FAILED_TESTS -gt 0 ]; then
        echo -e "${RED}Failed:       $FAILED_TESTS${NC}"
        echo ""
        print_error "Failed services:"
        for service in "${FAILED_SERVICES[@]}"; do
            echo "  - $service"
        done
        echo ""
        print_warning "Some services are not accessible or not implemented."
        print_info "Make sure all services are running and URLs are correct."
        exit 1
    else
        echo -e "${GREEN}Failed:       $FAILED_TESTS${NC}"
        echo ""
        print_success "All services passed! ✨"
        exit 0
    fi
}

# Check dependencies
check_dependencies() {
    if ! command -v curl &> /dev/null; then
        print_error "curl is required but not installed."
        exit 1
    fi

    if ! command -v jq &> /dev/null; then
        print_warning "jq not found. Install for better output formatting."
    fi
}

# Show usage
show_usage() {
    cat << EOF
Usage: $0 [OPTIONS] [tenant_id]

Test the tenant deletion system across all 12 microservices.

Options:
    -h, --help          Show this help message
    -v, --verbose       Show detailed response bodies
    -t, --tenant ID     Specify tenant ID to test (default: demo tenant)

Environment Variables:
    SERVICE_TOKEN       Service authentication token
    *_URL              Individual service URLs (e.g., ORDERS_URL)

Examples:
    # Test with default demo tenant
    $0

    # Test specific tenant
    $0 abc-123-def-456

    # Test with verbose output
    VERBOSE=1 $0

    # Test with custom service URLs
    ORDERS_URL=http://orders:8000/api/v1/orders $0

EOF
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_usage
            exit 0
            ;;
        -v|--verbose)
            VERBOSE=1
            shift
            ;;
        -t|--tenant)
            TENANT_ID="$2"
            shift 2
            ;;
        *)
            TENANT_ID="$1"
            shift
            ;;
    esac
done

# Run tests
check_dependencies
main
