#!/bin/bash

# Integration Test Runner for IAM Service
# This script sets up test infrastructure and runs integration tests

set -e

echo "🚀 Starting IAM Service Integration Tests"
echo "========================================="

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if Docker is running
if ! docker info >/dev/null 2>&1; then
    print_error "Docker is not running. Please start Docker first."
    exit 1
fi

# Set test environment variables
export TEST_DATABASE_URL="postgresql://test:test@localhost:5433/test_iam_db"
export TEST_REDIS_URL="redis://localhost:6380"
export NODE_ENV="test"
export LOG_LEVEL="error"  # Reduce log noise during tests
# Export DATABASE_URL for Prisma
export DATABASE_URL=$TEST_DATABASE_URL

print_status "Setting up test infrastructure..."

# Start test database containers
print_status "Starting PostgreSQL and Redis test containers..."
docker compose -f docker-compose.test.yml up -d

# Wait for databases to be ready
print_status "Waiting for PostgreSQL to be ready..."
timeout=60
counter=0
while ! docker exec postgres-test-iam pg_isready -U test -d test_iam_db >/dev/null 2>&1; do
    if [ $counter -gt $timeout ]; then
        print_error "PostgreSQL failed to start within ${timeout} seconds"
        docker compose -f docker-compose.test.yml logs postgres-test
        exit 1
    fi
    counter=$((counter + 1))
    sleep 1
done

print_status "Waiting for Redis to be ready..."
counter=0
while ! docker exec redis-test-iam redis-cli ping >/dev/null 2>&1; do
    if [ $counter -gt $timeout ]; then
        print_error "Redis failed to start within ${timeout} seconds"
        docker compose -f docker-compose.test.yml logs redis-test
        exit 1
    fi
    counter=$((counter + 1))
    sleep 1
done

print_success "Test infrastructure is ready!"

# Run database migrations
print_status "Running database migrations..."
# Assuming script is run from services/iam-service root if invoked via pnpm
# If invoked directly, we might need adjustment. But existing script does cd relative to script path.
# Let's keep existing cd logic but verify path.
SERVICE_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$SERVICE_ROOT"

if ! npx prisma migrate deploy --schema=prisma/schema.prisma; then
    print_error "Database migration failed"
    exit 1
fi

# Seed test data (optional - comment out if not needed)
# print_status "Seeding test data..."
# if ! pnpm prisma db seed; then
#     print_warning "Test data seeding failed, but continuing..."
# fi

# Run integration tests
print_status "Running integration tests..."
if npx jest -c jest.integration.config.ts --runInBand --verbose; then
    print_success "Integration tests passed!"
    TEST_RESULT=0
else
    print_error "Integration tests failed!"
    TEST_RESULT=1
fi

# Cleanup
print_status "Cleaning up test infrastructure..."
docker compose -f docker-compose.test.yml down -v

if [ $TEST_RESULT -eq 0 ]; then
    print_success "All integration tests completed successfully! 🎉"
    exit 0
else
    print_error "Integration tests failed! ❌"
    exit 1
fi