#!/bin/bash

# Desk-Moloni Integration Test Runner
# 
# Runs comprehensive tests for OAuth 2.0 and API client functionality
#
# Usage:
#   ./run-tests.sh                    # Run all tests
#   ./run-tests.sh oauth             # Run OAuth tests only
#   ./run-tests.sh api               # Run API client tests only
#   ./run-tests.sh contract          # Run contract tests only
#   ./run-tests.sh coverage          # Run with coverage report

set -e

# 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 directory
TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$TEST_DIR/../../../.." && pwd)"

echo -e "${BLUE}Desk-Moloni Integration Test Suite${NC}"
echo -e "${BLUE}===================================${NC}"
echo ""

# Check if PHPUnit is available
if ! command -v phpunit >/dev/null 2>&1; then
    echo -e "${RED}Error: PHPUnit not found${NC}"
    echo "Please install PHPUnit: https://phpunit.de/getting-started/"
    echo "Or install via Composer: composer global require phpunit/phpunit"
    exit 1
fi

# Check PHP version
PHP_VERSION=$(php -r "echo PHP_VERSION;")
echo -e "${BLUE}PHP Version:${NC} $PHP_VERSION"

# Check if required PHP extensions are loaded
echo -e "${BLUE}Checking PHP extensions...${NC}"
php -m | grep -E "(openssl|curl|json)" > /dev/null || {
    echo -e "${RED}Error: Required PHP extensions missing${NC}"
    echo "Required: openssl, curl, json"
    exit 1
}
echo -e "${GREEN}✓ Required PHP extensions found${NC}"

# Set environment variables for testing
export ENVIRONMENT=testing
export MOLONI_TEST_MODE=true
export CI_ENV=testing

# Function to run specific test suite
run_test_suite() {
    local suite=$1
    local description=$2
    
    echo ""
    echo -e "${YELLOW}Running $description...${NC}"
    echo "----------------------------------------"
    
    cd "$TEST_DIR"
    
    case $suite in
        "oauth")
            phpunit --testsuite "OAuth Integration" --verbose
            ;;
        "api")
            phpunit --testsuite "API Client Integration" --verbose
            ;;
        "contract")
            phpunit --testsuite "API Contract" --verbose
            ;;
        "coverage")
            phpunit --coverage-html coverage-html --coverage-text --coverage-clover coverage.xml
            ;;
        "all")
            phpunit --testsuite "All Tests" --verbose
            ;;
        *)
            echo -e "${RED}Unknown test suite: $suite${NC}"
            exit 1
            ;;
    esac
}

# Function to display test results
display_results() {
    echo ""
    echo -e "${BLUE}Test Results Summary${NC}"
    echo "===================="
    
    if [ -f "$TEST_DIR/test-results.xml" ]; then
        # Parse JUnit XML for summary (requires xmlstarlet or similar)
        if command -v xmlstarlet >/dev/null 2>&1; then
            local tests=$(xmlstarlet sel -t -v "//testsuite/@tests" "$TEST_DIR/test-results.xml" 2>/dev/null || echo "N/A")
            local failures=$(xmlstarlet sel -t -v "//testsuite/@failures" "$TEST_DIR/test-results.xml" 2>/dev/null || echo "N/A")
            local errors=$(xmlstarlet sel -t -v "//testsuite/@errors" "$TEST_DIR/test-results.xml" 2>/dev/null || echo "N/A")
            
            echo "Total Tests: $tests"
            echo "Failures: $failures"
            echo "Errors: $errors"
        fi
    fi
    
    # Check for coverage report
    if [ -f "$TEST_DIR/coverage.txt" ]; then
        echo ""
        echo "Coverage Report:"
        tail -n 5 "$TEST_DIR/coverage.txt"
    fi
    
    # Check for coverage HTML report
    if [ -d "$TEST_DIR/coverage-html" ]; then
        echo ""
        echo -e "${GREEN}HTML Coverage Report generated: $TEST_DIR/coverage-html/index.html${NC}"
    fi
}

# Function to cleanup old test artifacts
cleanup_artifacts() {
    echo -e "${BLUE}Cleaning up old test artifacts...${NC}"
    
    cd "$TEST_DIR"
    
    # Remove old coverage reports
    rm -rf coverage-html/
    rm -f coverage.xml coverage.txt
    
    # Remove old test results
    rm -f test-results.xml testdox.html testdox.txt teamcity.txt
    
    # Remove PHPUnit cache
    rm -rf .phpunit.cache .phpunit.result.cache
    
    echo -e "${GREEN}✓ Cleanup completed${NC}"
}

# Function to validate test environment
validate_environment() {
    echo -e "${BLUE}Validating test environment...${NC}"
    
    # Check if test files exist
    local test_files=(
        "OAuthIntegrationTest.php"
        "ApiClientIntegrationTest.php" 
        "MoloniApiContractTest.php"
        "phpunit.xml"
        "bootstrap.php"
    )
    
    for file in "${test_files[@]}"; do
        if [ ! -f "$TEST_DIR/$file" ]; then
            echo -e "${RED}Error: Test file not found: $file${NC}"
            exit 1
        fi
    done
    
    # Check if library files exist
    local library_files=(
        "../libraries/TokenManager.php"
        "../libraries/Moloni_oauth.php"
        "../libraries/MoloniApiClient.php"
    )
    
    for file in "${library_files[@]}"; do
        if [ ! -f "$TEST_DIR/$file" ]; then
            echo -e "${RED}Error: Library file not found: $file${NC}"
            exit 1
        fi
    done
    
    echo -e "${GREEN}✓ Test environment validated${NC}"
}

# Function to display help
show_help() {
    echo "Desk-Moloni Test Runner"
    echo ""
    echo "Usage: $0 [OPTION]"
    echo ""
    echo "Options:"
    echo "  oauth      Run OAuth integration tests only"
    echo "  api        Run API client integration tests only"
    echo "  contract   Run API contract tests only"
    echo "  coverage   Run all tests with coverage report"
    echo "  all        Run all test suites (default)"
    echo "  clean      Clean up test artifacts"
    echo "  help       Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0                    # Run all tests"
    echo "  $0 oauth             # Run OAuth tests only"
    echo "  $0 coverage          # Generate coverage report"
    echo ""
}

# Main execution
main() {
    local command=${1:-all}
    
    case $command in
        "help"|"-h"|"--help")
            show_help
            exit 0
            ;;
        "clean")
            cleanup_artifacts
            exit 0
            ;;
        "oauth"|"api"|"contract"|"coverage"|"all")
            validate_environment
            cleanup_artifacts
            
            case $command in
                "oauth")
                    run_test_suite "oauth" "OAuth Integration Tests"
                    ;;
                "api")
                    run_test_suite "api" "API Client Integration Tests"
                    ;;
                "contract")
                    run_test_suite "contract" "API Contract Tests"
                    ;;
                "coverage")
                    run_test_suite "coverage" "All Tests with Coverage"
                    ;;
                "all")
                    run_test_suite "all" "All Test Suites"
                    ;;
            esac
            
            display_results
            ;;
        *)
            echo -e "${RED}Error: Unknown command '$command'${NC}"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
}

# Error handling
trap 'echo -e "\n${RED}Test execution interrupted${NC}"; exit 1' INT TERM

# Run main function
main "$@"

echo ""
echo -e "${GREEN}Test execution completed!${NC}"