#!/bin/bash

# Run basic integration tests with test containers
# This is a comprehensive test that handles its own setup and teardown

set -e

cd "$(dirname "$0")"

echo "🚀 Running basic integration tests..."

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

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

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

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

# Cleanup function
cleanup() {
    print_status "Cleaning up test containers..."
    podman-compose -f podman-compose.yml down -v 2>/dev/null || true
}

# Set up cleanup trap
trap cleanup EXIT

# Start containers
print_status "Starting test containers..."
podman-compose -f podman-compose.yml up -d

# Wait for containers to be ready
print_status "Waiting for containers to be ready..."
sleep 10

# Check if CouchDB is ready
print_status "Checking CouchDB connectivity..."
timeout=30
while ! curl -s http://localhost:5984/_up > /dev/null 2>&1; do
    timeout=$((timeout - 1))
    if [ $timeout -le 0 ]; then
        print_error "CouchDB failed to start within 30 seconds"
        exit 1
    fi
    sleep 1
done
print_status "CouchDB is ready!"

# Check if IMAP server is ready
print_status "Checking IMAP server connectivity..."
timeout=30
while ! nc -z localhost 3143 > /dev/null 2>&1; do
    timeout=$((timeout - 1))
    if [ $timeout -le 0 ]; then
        print_error "IMAP server failed to start within 30 seconds"
        exit 1
    fi
    sleep 1
done
print_status "IMAP server is ready!"

# Populate test messages
print_status "Populating test messages..."
python3 ./populate-greenmail.py

# Build mail2couch
print_status "Building mail2couch..."
cd ../go
go build -o mail2couch .
cd ../test

# Run mail2couch with test configuration
print_status "Running mail2couch with test configuration..."
../go/mail2couch --config config-test.json --max-messages 3

# Verify results
print_status "Verifying test results..."

# Check CouchDB databases were created (using correct database names with m2c prefix)
EXPECTED_DBS=("m2c_wildcard_all_folders_test" "m2c_work_pattern_test" "m2c_specific_folders_only")

for db in "${EXPECTED_DBS[@]}"; do
    if curl -s "http://admin:password@localhost:5984/$db" | grep -q "\"db_name\":\"$db\""; then
        print_status "✅ Database '$db' created successfully"
    else
        print_error "❌ Database '$db' was not created"
        exit 1
    fi
done

# Check document counts
for db in "${EXPECTED_DBS[@]}"; do
    doc_count=$(curl -s "http://admin:password@localhost:5984/$db" | grep -o '"doc_count":[0-9]*' | cut -d':' -f2)
    if [ "$doc_count" -gt 0 ]; then
        print_status "✅ Database '$db' contains $doc_count documents"
    else
        print_warning "⚠️ Database '$db' contains no documents"
    fi
done

# Test sync mode by running again (should show incremental behavior)
print_status "Running mail2couch again to test incremental sync..."
../go/mail2couch --config config-test.json --max-messages 3

print_status "🎉 Basic integration tests completed successfully!"

# Show summary
print_status "Test Summary:"
echo "  - IMAP Server: localhost:3143"
echo "  - CouchDB: http://localhost:5984"
echo "  - Test accounts: testuser1, syncuser, archiveuser"
echo "  - Databases created: ${EXPECTED_DBS[*]}"
echo ""
echo "For more comprehensive tests, run:"
echo "  - ./test-wildcard-patterns.sh (test folder pattern matching)"
echo "  - ./test-incremental-sync.sh (test incremental synchronization)"