#!/bin/bash

# Change to the project directory
cd "$(dirname "$0")"

# Set environment variables
export LOG_DIR="$(pwd)/logs"

# Parse command line arguments
VERBOSE=false
DEPLOY=false
TESTSUITE=""
COVERAGE=false
PHPSTAN=false

while [[ "$#" -gt 0 ]]; do
    case $1 in
        -v|--verbose) VERBOSE=true ;;
        -d|--deploy) DEPLOY=true ;;
        --testsuite)
            if [[ -n "$2" && ! "$2" =~ ^- ]]; then
                TESTSUITE="$2"
                shift
            else
                echo "Error: --testsuite requires a value (unit, integration, or a testsuite name)"
                exit 1
            fi
            ;;
        --testsuite=*)
            TESTSUITE="${1#*=}"
            ;;
        --unit)
            TESTSUITE="unit"
            ;;
        --integration)
            TESTSUITE="integration"
            ;;
        --coverage)
            COVERAGE=true
            ;;
        --stan|--phpstan|--analyse)
            PHPSTAN=true
            ;;
        -h|--help)
            echo "Usage: ./test.sh [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  -v, --verbose       Run tests in verbose mode (show all warnings and notices)"
            echo "  -d, --deploy        Trigger Envoyer deployment after successful tests"
            echo "  --testsuite NAME    Run specific testsuite (unit, integration, or custom name)"
            echo "  --unit              Shorthand for --testsuite unit"
            echo "  --integration       Shorthand for --testsuite integration"
            echo "  --coverage          Generate HTML coverage report in coverage/"
            echo "  --stan              Run PHPStan static analysis after tests"
            echo "  -h, --help          Show this help message"
            echo ""
            echo "Examples:"
            echo "  ./test.sh                    # Run full test suite"
            echo "  ./test.sh --unit             # Run only unit tests"
            echo "  ./test.sh --integration      # Run only integration tests"
            echo "  ./test.sh --coverage         # Run tests with coverage report"
            echo "  ./test.sh -v --coverage      # Verbose tests with coverage"
            echo "  ./test.sh --stan             # Run tests then PHPStan analysis"
            echo "  ./test.sh -d                 # Run tests and deploy on success"
            exit 0
            ;;
        *) echo "Unknown parameter: $1. Use --help for usage information."; exit 1 ;;
    esac
    shift
done

# Ensure the logs directory exists
if [ ! -d "$LOG_DIR" ]; then
    echo "Creating logs directory: $LOG_DIR"
    mkdir -p "$LOG_DIR"
fi

echo "Running tests..."

# Run PHPUnit tests
cd userfrosting

# Build PHPUnit command arguments
PHPUNIT_ARGS=""

# Add testsuite flag if specified
if [ -n "$TESTSUITE" ]; then
    PHPUNIT_ARGS="$PHPUNIT_ARGS --testsuite $TESTSUITE"
    echo "Running testsuite: $TESTSUITE"
fi

# Add coverage flags if requested
if [ "$COVERAGE" = true ]; then
    COVERAGE_DIR="../coverage"
    PHPUNIT_ARGS="$PHPUNIT_ARGS --coverage-html $COVERAGE_DIR"
    echo "Coverage report will be generated in: $COVERAGE_DIR"
    # PHPUnit requires Xdebug coverage mode when collecting coverage
    export XDEBUG_MODE=coverage
else
    # Disable coverage to avoid "No code coverage driver available" warning
    PHPUNIT_ARGS="$PHPUNIT_ARGS --no-coverage"
fi

if [ "$VERBOSE" = true ]; then
    echo "Running in verbose mode (showing all warnings and notices)..."
    # Run full test suite using phpunit.xml configuration
    php vendor/bin/phpunit $PHPUNIT_ARGS
    PHPUNIT_EXIT_CODE=$?
else
    # Use -d error_reporting to suppress deprecation warnings
    # Run full test suite using phpunit.xml configuration
    php -d error_reporting=E_ALL\&~E_DEPRECATED\&~E_USER_DEPRECATED vendor/bin/phpunit $PHPUNIT_ARGS
    PHPUNIT_EXIT_CODE=$?
fi

cd - > /dev/null

# Check if tests failed
if [ ${PHPUNIT_EXIT_CODE} -ne 0 ]; then
    echo "Tests have failed!"
    exit 1
else
    echo "All tests passed!"

    # Run PHPStan if requested
    if [ "$PHPSTAN" = true ]; then
        echo ""
        echo "Running PHPStan static analysis..."
        cd userfrosting
        ./vendor/bin/phpstan analyse --memory-limit=2G
        PHPSTAN_EXIT_CODE=$?
        cd - > /dev/null

        if [ ${PHPSTAN_EXIT_CODE} -ne 0 ]; then
            echo ""
            echo "PHPStan found errors (see above). Tests passed but static analysis failed."
            exit 1
        else
            echo "PHPStan analysis passed!"
        fi
    fi

    # If deploy flag is set, trigger deployment
    if [ "$DEPLOY" = true ]; then
        # Check Vite build artifacts exist (if entry points are defined)
        echo ""
        echo "Checking Vite build artifacts..."
        php scripts/check-vite-dist.php
        VITE_CHECK_EXIT_CODE=$?

        if [ ${VITE_CHECK_EXIT_CODE} -ne 0 ]; then
            echo ""
            echo "Vite dist check failed. Run 'npm run build' and commit before deploying."
            exit 1
        fi

        echo "Triggering deployment..."
        # Replace the url below with your envoyer url
        curl -s 'https://envoyer.io/deploy/HLY5IPKkoPhwOAZjb31IhiK4fTbA7aJYw3eTZsqa'
        echo "Deployment triggered!"
    fi

    exit 0
fi
