#!/bin/bash
# ROA2WEB Docker Setup Test Script
# Validates Docker configuration before deployment

set -e

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

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

# Test results
TESTS_PASSED=0
TESTS_FAILED=0
ISSUES=()

# Logging function
log() {
    local level=$1
    shift
    local message="$*"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo -e "[$timestamp] [$level] $message"
}

# Test function
run_test() {
    local test_name=$1
    local test_command=$2
    
    echo -n "Testing $test_name... "
    
    if eval "$test_command" &>/dev/null; then
        echo -e "${GREEN}PASS${NC}"
        ((TESTS_PASSED++))
        return 0
    else
        echo -e "${RED}FAIL${NC}"
        ((TESTS_FAILED++))
        ISSUES+=("$test_name")
        return 1
    fi
}

# Test Docker availability
test_docker() {
    echo -e "${BLUE}=== Testing Docker Prerequisites ===${NC}"
    
    run_test "Docker installed" "command -v docker"
    run_test "Docker Compose installed" "command -v docker-compose"
    run_test "Docker daemon running" "docker info"
}

# Test file structure
test_file_structure() {
    echo -e "${BLUE}=== Testing File Structure ===${NC}"
    
    cd "$PROJECT_DIR"
    
    # Core Docker files
    run_test "Main docker-compose.yml exists" "test -f docker-compose.yml"
    run_test "Development override exists" "test -f docker-compose.override.yml"
    run_test "Production compose exists" "test -f docker-compose.production.yml"
    
    # Backend files
    run_test "Backend Dockerfile exists" "test -f backend/Dockerfile"
    run_test "Backend requirements exists" "test -f backend/requirements.txt"
    
    # Frontend files
    run_test "Frontend Dockerfile exists" "test -f src/Dockerfile"
    run_test "Frontend nginx.conf exists" "test -f src/nginx.conf"
    run_test "Frontend package.json exists" "test -f src/package.json"
    
    # Nginx Gateway files
    run_test "Nginx Gateway Dockerfile exists" "test -f nginx/Dockerfile"
    run_test "Nginx main config exists" "test -f nginx/conf/nginx.conf"
    run_test "Nginx upstream config exists" "test -f nginx/conf/upstream.conf"
    run_test "Nginx SSL config exists" "test -f nginx/conf/ssl.conf"
    run_test "Nginx security config exists" "test -f nginx/conf/security.conf"
    run_test "Nginx site config exists" "test -f nginx/conf/sites-enabled/roa2web.conf"
    
    # Scripts
    run_test "Deploy script exists" "test -f scripts/deploy.sh"
    run_test "Backup script exists" "test -f scripts/backup.sh"
    run_test "Rollback script exists" "test -f scripts/rollback.sh"
    run_test "Health check script exists" "test -f scripts/health-check.sh"
    
    # Scripts are executable
    run_test "Deploy script executable" "test -x scripts/deploy.sh"
    run_test "Backup script executable" "test -x scripts/backup.sh"
    run_test "Rollback script executable" "test -x scripts/rollback.sh"
    run_test "Health check script executable" "test -x scripts/health-check.sh"
    
    # Environment files
    run_test "Environment example exists" "test -f .env.example"
    run_test "Development env exists" "test -f .env.development"
    run_test "Production env exists" "test -f .env.production"
    
    # Documentation
    run_test "Docker setup guide exists" "test -f DOCKER_SETUP.md"
    run_test "Deployment guide exists" "test -f DEPLOYMENT_GUIDE.md"
    run_test "Production checklist exists" "test -f PRODUCTION_CHECKLIST.md"
}

# Test Docker Compose configuration
test_docker_compose() {
    echo -e "${BLUE}=== Testing Docker Compose Configuration ===${NC}"
    
    cd "$PROJECT_DIR"
    
    # Test main compose file
    run_test "Main compose config valid" "docker-compose config -q"
    
    # Test production compose
    run_test "Production compose config valid" "docker-compose -f docker-compose.yml -f docker-compose.production.yml config -q"
    
    # Test if all required services are defined
    run_test "Backend service defined" "docker-compose config | grep -q 'roa-backend:'"
    run_test "Frontend service defined" "docker-compose config | grep -q 'roa-frontend:'"
    run_test "Gateway service defined" "docker-compose config | grep -q 'roa-gateway:'"
    run_test "Redis service defined" "docker-compose config | grep -q 'roa-redis:'"
    
    # Test network configuration
    run_test "Custom network defined" "docker-compose config | grep -q 'roa-network:'"
    
    # Test volume configuration
    run_test "Nginx logs volume defined" "docker-compose config | grep -q 'nginx-logs:'"
    run_test "SSL certs volume defined" "docker-compose config | grep -q 'ssl-certs:'"
    run_test "Redis data volume defined" "docker-compose config | grep -q 'redis-data:'"
}

# Test environment configuration
test_environment() {
    echo -e "${BLUE}=== Testing Environment Configuration ===${NC}"
    
    cd "$PROJECT_DIR"
    
    # Check if development environment is complete
    if [[ -f .env.development ]]; then
        run_test "Development Oracle user set" "grep -q 'ORACLE_USER=' .env.development"
        run_test "Development JWT secret set" "grep -q 'JWT_SECRET_KEY=' .env.development"
        run_test "Development Redis password set" "grep -q 'REDIS_PASSWORD=' .env.development"
    fi
    
    # Check if production environment template is complete
    if [[ -f .env.production ]]; then
        run_test "Production domain configured" "grep -q 'DOMAIN=' .env.production"
        run_test "Production SSL email configured" "grep -q 'SSL_EMAIL=' .env.production"
        run_test "Production environment set" "grep -q 'ENVIRONMENT=production' .env.production"
    fi
    
    # Check secrets directory
    run_test "Secrets directory exists" "test -d secrets"
    run_test "Secrets gitkeep exists" "test -f secrets/.gitkeep"
}

# Test nginx configuration syntax
test_nginx_config() {
    echo -e "${BLUE}=== Testing Nginx Configuration ===${NC}"
    
    cd "$PROJECT_DIR"
    
    # Test nginx config syntax (if nginx is available)
    if command -v nginx &>/dev/null; then
        run_test "Nginx main config syntax" "nginx -t -c nginx/conf/nginx.conf -p $(pwd)/nginx/"
        run_test "Nginx site config syntax" "nginx -t -c nginx/conf/sites-enabled/roa2web.conf -p $(pwd)/nginx/"
    else
        log "WARNING" "Nginx not available for syntax testing"
    fi
    
    # Test config file content
    run_test "Nginx upstream config has backend" "grep -q 'roa_backend' nginx/conf/upstream.conf"
    run_test "Nginx upstream config has frontend" "grep -q 'roa_frontend' nginx/conf/upstream.conf"
    run_test "SSL config has protocols" "grep -q 'ssl_protocols' nginx/conf/ssl.conf"
    run_test "Security headers configured" "grep -q 'X-Frame-Options' nginx/conf/security.conf"
}

# Test scripts syntax
test_scripts() {
    echo -e "${BLUE}=== Testing Scripts Syntax ===${NC}"
    
    cd "$PROJECT_DIR"
    
    # Test bash script syntax
    run_test "Deploy script syntax" "bash -n scripts/deploy.sh"
    run_test "Backup script syntax" "bash -n scripts/backup.sh"
    run_test "Rollback script syntax" "bash -n scripts/rollback.sh"
    run_test "Health check script syntax" "bash -n scripts/health-check.sh"
    
    # Test if scripts have proper shebangs
    run_test "Deploy script has shebang" "head -1 scripts/deploy.sh | grep -q '#!/bin/bash'"
    run_test "Backup script has shebang" "head -1 scripts/backup.sh | grep -q '#!/bin/bash'"
    run_test "Rollback script has shebang" "head -1 scripts/rollback.sh | grep -q '#!/bin/bash'"
    run_test "Health check script has shebang" "head -1 scripts/health-check.sh | grep -q '#!/bin/bash'"
}

# Generate test report
generate_report() {
    echo ""
    echo -e "${BLUE}=== Test Results Summary ===${NC}"
    echo ""
    
    local total_tests=$((TESTS_PASSED + TESTS_FAILED))
    
    echo -e "Total tests run: ${BLUE}$total_tests${NC}"
    echo -e "Tests passed: ${GREEN}$TESTS_PASSED${NC}"
    echo -e "Tests failed: ${RED}$TESTS_FAILED${NC}"
    
    if [[ $TESTS_FAILED -eq 0 ]]; then
        echo ""
        echo -e "${GREEN}✅ ALL TESTS PASSED! Docker setup is ready for deployment.${NC}"
        echo ""
        echo -e "${BLUE}Next steps:${NC}"
        echo "1. Copy .env.development to .env for local development"
        echo "2. Configure your Oracle database credentials"
        echo "3. Run: docker-compose up --build"
        echo ""
        return 0
    else
        echo ""
        echo -e "${RED}❌ Some tests failed. Please fix the following issues:${NC}"
        echo ""
        for issue in "${ISSUES[@]}"; do
            echo -e "  ${RED}•${NC} $issue"
        done
        echo ""
        echo -e "${YELLOW}Please fix these issues before proceeding with deployment.${NC}"
        return 1
    fi
}

# Main test execution
main() {
    echo -e "${BLUE}ROA2WEB Docker Setup Test Suite${NC}"
    echo -e "${BLUE}================================${NC}"
    echo ""
    
    test_docker
    echo ""
    
    test_file_structure
    echo ""
    
    if command -v docker-compose &>/dev/null; then
        test_docker_compose
        echo ""
    else
        log "WARNING" "Docker Compose not available, skipping compose tests"
    fi
    
    test_environment
    echo ""
    
    test_nginx_config
    echo ""
    
    test_scripts
    echo ""
    
    generate_report
}

# Run main function
main "$@"