#!/bin/bash

# Script to run the subscription creation integration test inside Kubernetes
# This script creates a test pod that runs the integration test

set -e

echo "🚀 Starting subscription creation integration test..."

# Check if there's already a test pod running
EXISTING_POD=$(kubectl get pod subscription-integration-test -n bakery-ia 2>/dev/null || echo "")
if [ -n "$EXISTING_POD" ]; then
  echo "🧹 Cleaning up existing test pod..."
  kubectl delete pod subscription-integration-test -n bakery-ia --wait=true
  echo "✅ Existing pod cleaned up"
fi

# Determine the correct image to use by checking the existing tenant service deployment
IMAGE=$(kubectl get deployment tenant-service -n bakery-ia -o jsonpath='{.spec.template.spec.containers[0].image}')

if [ -z "$IMAGE" ]; then
  echo "❌ Could not determine tenant service image. Is the tenant service deployed?"
  exit 1
fi

echo "📦 Using image: $IMAGE"

# Create a test pod that runs the integration test with a simple command
echo "🔧 Creating test pod..."
kubectl run subscription-integration-test \
  --image="$IMAGE" \
  --namespace=bakery-ia \
  --restart=Never \
  --env="GATEWAY_URL=http://gateway-service:8000" \
  --env="STRIPE_SECRET_KEY=$(kubectl get secret payment-secrets -n bakery-ia -o jsonpath='{.data.STRIPE_SECRET_KEY}' | base64 -d)" \
  --command -- /bin/sh -c "
    set -e
    echo '🧪 Setting up test environment...' &&
    cd /app &&
    echo '📋 Installing test dependencies...' &&
    pip install pytest pytest-asyncio httpx stripe --quiet &&
    echo '✅ Dependencies installed' &&
    echo '' &&
    echo '🔧 Configuring test to use internal gateway service URL...' &&
    # Backup original file before modification
    cp tests/integration/test_subscription_creation_flow.py tests/integration/test_subscription_creation_flow.py.bak &&
    # Update the test file to use the internal gateway service URL
    sed -i 's|self.base_url = \"https://bakery-ia.local\"|self.base_url = \"http://gateway-service:8000\"|g' tests/integration/test_subscription_creation_flow.py &&
    echo '✅ Test configured for internal Kubernetes networking' &&
    echo '' &&
    echo '🧪 Running subscription creation integration test...' &&
    echo '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' &&
    python -m pytest tests/integration/test_subscription_creation_flow.py -v --tb=short -s --color=yes &&
    TEST_RESULT=\$? &&
    echo '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' &&
    echo '' &&
    echo '📋 Restoring original test file...' &&
    mv tests/integration/test_subscription_creation_flow.py.bak tests/integration/test_subscription_creation_flow.py &&
    echo '✅ Original test file restored' &&
    echo '' &&
    if [ \$TEST_RESULT -eq 0 ]; then
      echo '🎉 Integration test PASSED!'
    else
      echo '❌ Integration test FAILED!'
    fi &&
    exit \$TEST_RESULT
  "

# Wait for the test pod to start
echo "⏳ Waiting for test pod to start..."
sleep 5

# Follow the logs in real-time
echo "📋 Following test execution logs..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Stream logs while the pod is running
kubectl logs -f subscription-integration-test -n bakery-ia 2>/dev/null || true

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Wait for the pod to complete with a timeout
echo "⏳ Waiting for test pod to complete..."
TIMEOUT=600  # 10 minutes timeout
COUNTER=0
while [ $COUNTER -lt $TIMEOUT ]; do
  POD_STATUS=$(kubectl get pod subscription-integration-test -n bakery-ia -o jsonpath='{.status.phase}' 2>/dev/null)

  if [ "$POD_STATUS" == "Succeeded" ] || [ "$POD_STATUS" == "Failed" ]; then
    break
  fi

  sleep 2
  COUNTER=$((COUNTER + 2))
done

if [ $COUNTER -ge $TIMEOUT ]; then
  echo "⏰ Timeout waiting for test to complete after $TIMEOUT seconds"
  echo "📋 Fetching final logs before cleanup..."
  kubectl logs subscription-integration-test -n bakery-ia --tail=100
  echo "🧹 Cleaning up test pod due to timeout..."
  kubectl delete pod subscription-integration-test -n bakery-ia --wait=false
  exit 1
fi

# Get the final status
POD_STATUS=$(kubectl get pod subscription-integration-test -n bakery-ia -o jsonpath='{.status.phase}')
CONTAINER_EXIT_CODE=$(kubectl get pod subscription-integration-test -n bakery-ia -o jsonpath='{.status.containerStatuses[0].state.terminated.exitCode}' 2>/dev/null || echo "unknown")

echo ""
echo "📊 Test Results:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Pod Status: $POD_STATUS"
echo "Exit Code: $CONTAINER_EXIT_CODE"

# Determine if the test passed
if [ "$POD_STATUS" == "Succeeded" ] && [ "$CONTAINER_EXIT_CODE" == "0" ]; then
  echo ""
  echo "✅ Integration test PASSED!"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  RESULT=0
else
  echo ""
  echo "❌ Integration test FAILED!"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

  # Show additional logs if failed
  if [ "$POD_STATUS" == "Failed" ]; then
    echo ""
    echo "📋 Last 50 lines of logs:"
    kubectl logs subscription-integration-test -n bakery-ia --tail=50
  fi

  RESULT=1
fi

# Clean up the test pod
echo ""
echo "🧹 Cleaning up test pod..."
kubectl delete pod subscription-integration-test -n bakery-ia --wait=false

echo "🏁 Integration test process completed!"
exit $RESULT