#!/bin/bash

# VIP Coordinator Test Runner Script

set -e

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

# Test type from argument
TEST_TYPE=${1:-all}

# Functions
print_header() {
    echo -e "${GREEN}=== $1 ===${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_info() {
    echo -e "${YELLOW}ℹ️  $1${NC}"
}

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

# Run backend tests
run_backend_tests() {
    print_header "Running Backend Tests"
    
    # Start test database and Redis
    docker-compose -f docker-compose.test.yml up -d test-db test-redis
    
    # Wait for services to be ready
    print_info "Waiting for test database..."
    sleep 5
    
    # Run tests
    docker-compose -f docker-compose.test.yml run --rm backend-test
    
    # Cleanup
    docker-compose -f docker-compose.test.yml down
}

# Run frontend tests
run_frontend_tests() {
    print_header "Running Frontend Tests"
    
    # Run tests
    docker-compose -f docker-compose.test.yml run --rm frontend-test
}

# Run E2E tests
run_e2e_tests() {
    print_header "Running E2E Tests"
    
    # Start all services for E2E
    docker-compose -f docker-compose.test.yml up -d backend frontend
    
    # Wait for services
    print_info "Waiting for services to be ready..."
    sleep 10
    
    # Run E2E tests
    docker-compose -f docker-compose.test.yml run --rm e2e-test
    
    # Cleanup
    docker-compose -f docker-compose.test.yml down
}

# Run all tests
run_all_tests() {
    print_header "Running All Tests"
    
    run_backend_tests
    run_frontend_tests
    run_e2e_tests
    
    print_success "All tests completed!"
}

# Generate coverage report
generate_coverage() {
    print_header "Generating Coverage Reports"
    
    # Backend coverage
    docker-compose -f docker-compose.test.yml run --rm \
        backend-test npm run test:coverage
    
    # Frontend coverage
    docker-compose -f docker-compose.test.yml run --rm \
        frontend-test npm run test:coverage
    
    print_info "Coverage reports generated in coverage/ directories"
}

# Main execution
check_docker

case $TEST_TYPE in
    backend)
        run_backend_tests
        ;;
    frontend)
        run_frontend_tests
        ;;
    e2e)
        run_e2e_tests
        ;;
    coverage)
        generate_coverage
        ;;
    all)
        run_all_tests
        ;;
    *)
        echo "Usage: $0 [backend|frontend|e2e|coverage|all]"
        exit 1
        ;;
esac

print_success "Test run completed!"