#!/bin/bash

# Start test environment for manual testing

cd "$(dirname "$0")"

echo "🚀 Starting mail2couch test environment..."

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

# Wait for services
echo "Waiting for services to be ready..."
sleep 10

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

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

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

echo ""
echo "🎉 Test environment is ready!"
echo ""
echo "Services:"
echo "  - CouchDB: http://localhost:5984 (admin/password)"
echo "  - CouchDB Web UI: http://localhost:5984/_utils"
echo "  - IMAP Server: localhost:3143"
echo "  - IMAPS Server: localhost:3993"
echo "  - SMTP Server: localhost:3025"
echo ""
echo "Test accounts:"
echo "  - testuser1:password123"
echo "  - testuser2:password456"
echo "  - syncuser:syncpass"
echo "  - archiveuser:archivepass"
echo ""
echo "To run mail2couch:"
echo "  cd ../go && ./mail2couch -config ../test/config-test.json"
echo ""
echo "📧 MAIL2COUCH DATABASE ACCESS:"
echo "After running mail2couch, you can access the stored emails via CouchDB:"
echo ""
echo "📋 Database Access (examples after sync):"
echo "  - All databases: http://localhost:5984/_all_dbs"
echo "  - Specific database: http://localhost:5984/m2c_specific_folders_only"
echo "  - All documents: http://localhost:5984/m2c_specific_folders_only/_all_docs"
echo "  - Individual message: http://localhost:5984/m2c_specific_folders_only/INBOX_12"
echo ""
echo "🔍 Raw Data Access:"
echo "  - Database info: http://localhost:5984/m2c_specific_folders_only"
echo "  - Document with content: http://localhost:5984/m2c_specific_folders_only/INBOX_12"
echo ""
echo "To stop the environment:"
echo "  ./stop-test-env.sh"