#!/bin/bash
# Setup script for integration tests
# Ensures test environment is ready (PostgreSQL, Redis, API keys)

set -e

echo "========================================="
echo "Setting up test environment"
echo "========================================="

# Check if docker-compose is available
if command -v docker-compose &> /dev/null; then
    echo "✓ docker-compose found"
    
    # Start test services
    echo "Starting test services (PostgreSQL, Redis)..."
    docker-compose -f infra/docker-compose.yml up -d postgres redis
    
    # Wait for services to be ready
    echo "Waiting for PostgreSQL..."
    timeout 30 bash -c 'until docker-compose -f infra/docker-compose.yml exec -T postgres pg_isready -U postgres; do sleep 1; done' || exit 1
    
    echo "Waiting for Redis..."
    timeout 30 bash -c 'until docker-compose -f infra/docker-compose.yml exec -T redis redis-cli ping; do sleep 1; done' || exit 1
    
    echo "✓ Test services ready"
else
    echo "⚠️  docker-compose not found. Assuming services are running manually."
fi

# Check if test API key exists
if [ -z "$TEST_API_KEY" ]; then
    echo "⚠️  TEST_API_KEY not set. Using default test key."
    export TEST_API_KEY="test-key-ce67dabb0d4e27e3d72877c921b89cae"
fi

# Set default test server URL if not set
if [ -z "$TEST_SERVER_URL" ]; then
    export TEST_SERVER_URL="http://localhost:3000"
    echo "⚠️  TEST_SERVER_URL not set. Using default: $TEST_SERVER_URL"
fi

# Check if server is running
echo "Checking if gateway server is running..."
if curl -s "$TEST_SERVER_URL/health" > /dev/null; then
    echo "✓ Gateway server is running"
else
    echo "⚠️  Gateway server is not running at $TEST_SERVER_URL"
    echo "   Start it with: docker-compose -f infra/docker-compose.yml up -d gateway"
    echo "   Or: cd apps/gateway && pnpm start"
fi

echo ""
echo "========================================="
echo "Test environment setup complete"
echo "========================================="
echo ""
echo "Environment variables:"
echo "  TEST_SERVER_URL=$TEST_SERVER_URL"
echo "  TEST_API_KEY=$TEST_API_KEY"
echo "  TEST_DATABASE_URL=${TEST_DATABASE_URL:-not set}"
echo "  TEST_REDIS_URL=${TEST_REDIS_URL:-not set}"
echo ""
echo "Run integration tests:"
echo "  cd apps/gateway && pnpm test:integration"
echo ""

