#!/bin/bash
# Run Integration Tests with Automatic Setup
# Checks for credentials and provides setup instructions if missing

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

cd "$(dirname "$0")/../.."

log_info "Entra VerifiedID Integration Test Runner"
echo ""

# Check for environment variables
MISSING_VARS=()

check_var() {
    local var=$1
    if [ -z "${!var:-}" ]; then
        MISSING_VARS+=("${var}")
        return 1
    fi
    return 0
}

check_var "ENTRA_TENANT_ID" || true
check_var "ENTRA_CLIENT_ID" || true
check_var "ENTRA_CLIENT_SECRET" || true
check_var "ENTRA_CREDENTIAL_MANIFEST_ID" || true

if [ ${#MISSING_VARS[@]} -gt 0 ]; then
    log_warning "Missing required environment variables:"
    for var in "${MISSING_VARS[@]}"; do
        echo "  - ${var}"
    done
    echo ""
    log_info "To set up credentials:"
    echo "1. Run: ./scripts/deploy/setup-entra-automated.sh"
    echo "2. Or manually set environment variables:"
    echo "   export ENTRA_TENANT_ID=<tenant-id>"
    echo "   export ENTRA_CLIENT_ID=<client-id>"
    echo "   export ENTRA_CLIENT_SECRET=<client-secret>"
    echo "   export ENTRA_CREDENTIAL_MANIFEST_ID=<manifest-id>"
    echo ""
    log_info "Loading from .env file if available..."
    if [ -f ".env" ]; then
        set -a
        source .env
        set +a
        log_info "Loaded from .env"
    fi
    
    # Re-check
    MISSING_VARS=()
    check_var "ENTRA_TENANT_ID" || true
    check_var "ENTRA_CLIENT_ID" || true
    check_var "ENTRA_CLIENT_SECRET" || true
    check_var "ENTRA_CREDENTIAL_MANIFEST_ID" || true
    
    if [ ${#MISSING_VARS[@]} -gt 0 ]; then
        log_error "Still missing required variables. Cannot run integration tests."
        exit 1
    fi
fi

log_success "All required environment variables are set"
echo ""

# Run integration tests
log_info "Running integration tests..."
echo ""

if pnpm --filter @the-order/auth test entra-verifiedid.integration.test.ts --run 2>&1 | tee /tmp/integration-test.log; then
    log_success "Integration tests passed!"
    exit 0
else
    log_error "Integration tests failed"
    log_info "Check /tmp/integration-test.log for details"
    exit 1
fi

