#!/bin/bash

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

echo "Starting Integration Test..."

# 1. Wait for services
echo "Waiting for services to be ready..."
sleep 10 # Simple wait, in real world use health checks

# 2. Create Key via Control Plane (ez-api)
echo "Creating Key via ez-api..."
KEY_SECRET="sk-test-integration-$(date +%s)"
# Note: Keys route by group now; omitting group defaults to "default".
RESPONSE=$(curl -s -X POST http://localhost:8080/keys \
  -H "Content-Type: application/json" \
  -d "{\"key_secret\": \"$KEY_SECRET\", \"balance\": 100.0, \"group\": \"default\"}")

echo "Create Key Response: $RESPONSE"

if [[ $RESPONSE == *"KeySecret"* ]]; then
    echo -e "${GREEN}Key Created Successfully${NC}"
else
    echo -e "${RED}Failed to Create Key${NC}"
    exit 1
fi

# 3. Verify Auth via Data Plane (balancer)
echo "Verifying Auth via balancer..."
# Note: We are hitting /v1/chat/completions. Since we don't have a real upstream, 
# we expect 502 Bad Gateway (if upstream is down) or 404/200 from upstream.
# But definitely NOT 401 Unauthorized.

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:8081/v1/chat/completions \
  -H "Authorization: Bearer $KEY_SECRET" \
  -H "Content-Type: application/json" \
  -d "{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]}")

echo "Balancer HTTP Code: $HTTP_CODE"

if [[ "$HTTP_CODE" == "401" ]]; then
    echo -e "${RED}Auth Failed: Got 401 Unauthorized${NC}"
    exit 1
elif [[ "$HTTP_CODE" == "502" || "$HTTP_CODE" == "200" || "$HTTP_CODE" == "404" ]]; then
    # 502 means Auth passed but upstream failed (expected in test env without real internet/upstream)
    echo -e "${GREEN}Auth Passed (Upstream response: $HTTP_CODE)${NC}"
else
    echo -e "${RED}Unexpected Response: $HTTP_CODE${NC}"
    exit 1
fi

echo -e "${GREEN}Integration Test Passed!${NC}"
