#!/bin/bash
# Quick test script for deletion endpoints via localhost (port-forwarded or ingress)
# This tests with the real Bakery-IA demo tenant

set -e

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

# Demo tenant from the system
TENANT_ID="dbc2128a-7539-470c-94b9-c1e37031bd77"
DEMO_SESSION_ID="demo_8rkT9JjXWFuVmdqT798Nyg"

# Base URL (through ingress or port-forward)
BASE_URL="${BASE_URL:-https://localhost}"

echo -e "${BLUE}Testing Deletion System with Real Services${NC}"
echo -e "${BLUE}===========================================${NC}"
echo ""
echo -e "Tenant ID: ${YELLOW}$TENANT_ID${NC}"
echo -e "Base URL:  ${YELLOW}$BASE_URL${NC}"
echo ""

# Test function
test_service() {
    local service_name=$1
    local endpoint=$2

    echo -n "Testing $service_name... "

    # Try to access the deletion preview endpoint
    response=$(curl -k -s -w "\n%{http_code}" \
        -H "X-Demo-Session-Id: $DEMO_SESSION_ID" \
        -H "X-Tenant-ID: $TENANT_ID" \
        "$BASE_URL$endpoint/tenant/$TENANT_ID/deletion-preview" 2>&1)

    http_code=$(echo "$response" | tail -1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" = "200" ]; then
        # Try to parse total records
        total=$(echo "$body" | grep -o '"total_records":[0-9]*' | cut -d':' -f2 || echo "?")
        echo -e "${GREEN}✓${NC} (HTTP $http_code, Records: $total)"
    elif [ "$http_code" = "401" ] || [ "$http_code" = "403" ]; then
        echo -e "${YELLOW}⚠${NC} (HTTP $http_code - Auth required)"
    elif [ "$http_code" = "404" ]; then
        echo -e "${RED}✗${NC} (HTTP $http_code - Endpoint not found)"
    else
        echo -e "${RED}✗${NC} (HTTP $http_code)"
    fi
}

# Test all services
echo "Testing deletion preview endpoints:"
echo ""

test_service "Orders" "/api/v1/orders"
test_service "Inventory" "/api/v1/inventory"
test_service "Recipes" "/api/v1/recipes"
test_service "Sales" "/api/v1/sales"
test_service "Production" "/api/v1/production"
test_service "Suppliers" "/api/v1/suppliers"
test_service "POS" "/api/v1/pos"
test_service "External" "/api/v1/external"
test_service "Forecasting" "/api/v1/forecasting"
test_service "Training" "/api/v1/training"
test_service "Alert Processor" "/api/v1/alerts"
test_service "Notification" "/api/v1/notifications"

echo ""
echo -e "${BLUE}Test completed!${NC}"
echo ""
echo -e "${YELLOW}Note:${NC} 401/403 responses are expected - deletion endpoints require service tokens"
echo -e "${YELLOW}Note:${NC} To test with proper auth, set up service-to-service authentication"
