#!/bin/bash

# IAM Service Integration Test Runner
# This script sets up a test environment and runs integration tests

set -e

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

# Check if PostgreSQL is available (using the test setup from docker-compose.test.yml)
if ! docker ps | grep -q postgres-test-iam; then
    echo "⚠️  PostgreSQL test container not running. Starting it..."
    docker-compose -f docker-compose.test.yml up -d postgres-test
    sleep 10
fi

# Check if Redis is available
if ! docker ps | grep -q redis-test-iam; then
    echo "⚠️  Redis test container not running. Starting it..."
    docker-compose -f docker-compose.test.yml up -d redis-test
    sleep 5
fi

# Set test environment variables
export NODE_ENV="test"
export DATABASE_URL="postgresql://test:test@localhost:5433/test_iam_db"
export REDIS_URL="redis://localhost:6380"
export JWT_SECRET="test-jwt-secret-for-integration-tests"
export JWT_REFRESH_SECRET="test-refresh-secret-for-integration-tests"

echo "🔧 Setting up test database..."

# Run database migrations
if ! npx prisma migrate deploy --schema=prisma/schema.prisma; then
    echo "❌ Database migration failed"
    exit 1
fi

echo "✅ Database migrations completed"

# Run the integration tests
echo "🧪 Running integration tests..."
if npm test -- --testPathPattern="integration" --testTimeout=60000 --verbose; then
    echo "✅ Integration tests passed!"
    exit 0
else
    echo "❌ Integration tests failed!"
    exit 1
fi