#!/bin/bash

# Load environment variables
if [ ! -f ./.env ]; then
    echo "Error: .env file not found!"
    exit 1
fi

echo "Sourcing .env file from: $(pwd)/.env"
source ./.env

# Change to the script's directory parent (wordpress-dev)
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) # Corrected: &> and &&
cd "$SCRIPT_DIR/.." || exit 1
echo "Changed working directory to: $(pwd)"

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

# Default values
RUN_UNIT=false
RUN_INTEGRATION=false
RUN_E2E=false
DEBUG=false
TEST_SUITE=""
PHPUNIT_FILTER=""

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --unit)
            RUN_UNIT=true
            shift
            ;;
        --integration)
            RUN_INTEGRATION=true
            shift
            ;;
        --e2e)
            RUN_E2E=true
            shift
            ;;
        --login)
            RUN_E2E=true
            TEST_SUITE="login"
            shift
            ;;
        --trainer-journey)
            RUN_E2E=true
            TEST_SUITE="trainer-journey"
            shift
            ;;
        --debug)
            DEBUG=true
            shift
            ;;
        --filter)
            if [[ -z "$2" || "$2" == --* ]]; then
                echo "Error: --filter option requires a value."
                exit 1
            fi
            PHPUNIT_FILTER="$2"
            shift 2 # Consume both --filter and its value
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# If no test type specified, run all
if ! $RUN_UNIT && ! $RUN_INTEGRATION && ! $RUN_E2E; then # Corrected: &&
    RUN_UNIT=true
    RUN_INTEGRATION=true
    RUN_E2E=true
fi

# Function to run tests
run_tests() {
    local test_type=$1
    local test_command=$2

    echo -e "${YELLOW}Running $test_type tests...${NC}"
    if $DEBUG; then
        echo "Test command: $test_command"
    fi

    if eval $test_command; then
        echo -e "${GREEN}✓ $test_type tests passed${NC}"
        return 0
    else
        echo -e "${RED}✗ $test_type tests failed. Exiting.${NC}"
        exit 1 # Exit script immediately on failure
    fi
}

# Create results directory
mkdir -p ../test-results

# Composer dependencies are managed on the host and mounted via volume.

# Run unit tests using relative path via docker-compose exec
if $RUN_UNIT; then
    # Base command
    UNIT_CMD="vendor/bin/phpunit --verbose --testsuite unit --log-junit ../test-results/unit.xml"
    # Add filter if provided, ensuring proper quoting for the value
    if [ -n "$PHPUNIT_FILTER" ]; then
        # Escape potential special characters within the filter value for sh -c
        FILTER_ESCAPED=$(printf '%s\n' "$PHPUNIT_FILTER" | sed "s/'/'\\\\''/g")
        UNIT_CMD="$UNIT_CMD --filter '$FILTER_ESCAPED'"
    fi
    # Add command to capture exit status
    UNIT_CMD="$UNIT_CMD; exit \$?"
    # Execute the command via sh -c, passing the constructed command in single quotes
	run_tests "Unit" "docker-compose exec -T wordpress sh -c '$UNIT_CMD'"
fi

# Run integration tests using relative path via docker-compose exec
if $RUN_INTEGRATION; then
    # Base command
    INTEGRATION_CMD="vendor/bin/phpunit --testsuite integration --log-junit ../test-results/integration.xml"
    # Add filter if provided
    if [ -n "$PHPUNIT_FILTER" ]; then
        FILTER_ESCAPED=$(printf '%s\n' "$PHPUNIT_FILTER" | sed "s/'/'\\\\''/g")
        INTEGRATION_CMD="$INTEGRATION_CMD --filter '$FILTER_ESCAPED'"
    fi
    # Add command to capture exit status
    INTEGRATION_CMD="$INTEGRATION_CMD; exit \$?"
    # Execute the command via sh -c
	run_tests "Integration" "docker-compose exec -T wordpress sh -c '$INTEGRATION_CMD'"
fi

# Run E2E tests
if $RUN_E2E; then
    # Ensure plugin activation hooks run and permalinks are fresh for E2E context
    echo -e "${YELLOW}Deactivating/Reactivating plugin to ensure hooks fire...${NC}"
    sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp plugin deactivate hvac-community-events --allow-root" || echo -e "${YELLOW}Note: Plugin already inactive or not found (continuing).${NC}" # Allow failure if already inactive
    sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp plugin activate hvac-community-events --allow-root"
    if [ $? -ne 0 ]; then
        echo -e "${RED}✗ Failed to activate hvac-community-events plugin. Exiting.${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Plugin reactivated.${NC}"

    # Flush rewrite rules after activation
    echo -e "${YELLOW}Flushing rewrite rules...${NC}"
    if ! sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp rewrite flush --hard --allow-root"; then
        echo -e "${RED}✗ Failed to flush rewrite rules. Exiting.${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Rewrite rules flushed.${NC}"

    # Now run the tests
    if [ -n "$TEST_SUITE" ]; then
        # Run specific test suite
        if [ "$TEST_SUITE" == "trainer-journey" ]; then
            UPSKILL_STAGING_URL="$UPSKILL_STAGING_URL" npx playwright test --config=playwright.config.ts tests/e2e/trainer-journey.test.ts
        else
            UPSKILL_STAGING_URL="$UPSKILL_STAGING_URL" npx playwright test --config=playwright.config.ts --grep "@$TEST_SUITE"
        fi
    else
        # Run all E2E tests
        echo "Current working directory: $(pwd)"
        # Run all E2E tests
        TEST_FILE_PATH="/Users/ben/dev/upskill-event-manager/wordpress-dev/tests/e2e/homepage.test.ts"
        echo "Current working directory: $(pwd)"
        echo "Executing command: UPSKILL_STAGING_URL=\"$UPSKILL_STAGING_URL\" npx playwright test --config=tests/e2e/playwright.config.ts $TEST_FILE_PATH"
        UPSKILL_STAGING_URL="$UPSKILL_STAGING_URL" npx playwright test --config=tests/e2e/playwright.config.ts "$TEST_FILE_PATH"
    fi
fi
