#!/bin/bash

# Advanced Playwright Test Runner
# This script runs Playwright tests with enhanced setup and config options
# Usage: ./bin/run-advanced-tests.sh [--test TEST_TYPE] [--headed] [--debug] [--ui]
#
# Test types:
#   basic      - Basic certificate tests (default)
#   journey    - Full trainer journey with certificates
#   cert       - Certificate generation
#   cert-gen   - Certificate generation for checked-in attendees
#   all        - All certificate tests

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

# Change to the project root directory
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd "$SCRIPT_DIR/.." || exit 1
echo "Changed working directory to: $(pwd)"

# Display banner
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}      Advanced Playwright Test Runner       ${NC}"
echo -e "${BLUE}============================================${NC}"

# Parse command line arguments
TEST_TYPE="basic"
UI_MODE=""
DEBUG_MODE=""
UI_INSPECTOR=""

while [[ "$#" -gt 0 ]]; do
  case $1 in
    --test)
      TEST_TYPE="$2"
      shift 2
      ;;
    --headed)
      UI_MODE="--headed"
      shift
      ;;
    --debug)
      DEBUG_MODE="--debug"
      shift
      ;;
    --ui)
      UI_INSPECTOR="--ui"
      shift
      ;;
    *)
      echo -e "${RED}Unknown parameter: $1${NC}"
      echo "Usage: ./bin/run-advanced-tests.sh [--test TEST_TYPE] [--headed] [--debug] [--ui]"
      echo "Test types: basic, journey, cert, cert-gen, all"
      exit 1
      ;;
  esac
done

# Load environment variables
if [ -f ./.env ]; then
  echo "Loading environment variables from .env"
  source ./.env
else
  echo -e "${RED}Error: .env file not found!${NC}"
  echo "Make sure you have a .env file with the required environment variables"
  exit 1
fi

# Verify plugin is activated
echo -e "${YELLOW}Verifying plugin activation...${NC}"
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp plugin is-active hvac-community-events --allow-root"

if [ $? -ne 0 ]; then
  echo -e "${YELLOW}Plugin not active. Activating hvac-community-events...${NC}"
  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 plugin. Cannot continue.${NC}"
    exit 1
  fi
  
  # Flush rewrite rules
  echo -e "${YELLOW}Flushing rewrite rules...${NC}"
  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"
else
  echo -e "${GREEN}Plugin is active.${NC}"
fi

# Check if test user exists
echo -e "${YELLOW}Checking test user...${NC}"
USER_EXISTS=$(sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp user get test_trainer --field=ID --allow-root 2>/dev/null || echo 'notfound'")

if [ "$USER_EXISTS" == "notfound" ]; then
  echo -e "${YELLOW}Test user not found. Creating test user...${NC}"
  # Run the setup script
  ./bin/setup-staging-test-users.sh
else
  echo -e "${GREEN}Test user found with ID: $USER_EXISTS${NC}"
fi

# Clear cache if needed
echo -e "${YELLOW}Clearing cache...${NC}"
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp cache flush --allow-root"

# Determine test to run
case $TEST_TYPE in
  "basic")
    TEST_FILE="tests/e2e/certificate-basic.spec.ts"
    TEST_DESC="Basic certificate tests"
    ;;
  "journey")
    TEST_FILE="tests/e2e/trainer-journey-harmonized.test.ts"
    TEST_DESC="Full trainer journey with certificates"
    ;;
  "cert")
    TEST_FILE="tests/e2e/certificates.test.ts"
    TEST_DESC="Certificate tests"
    ;;
  "cert-gen")
    TEST_FILE="tests/e2e/certificate-generation-checked-in.test.ts"
    TEST_DESC="Certificate generation for checked-in attendees"
    ;;
  "all")
    TEST_FILE="tests/e2e/certificate*.{ts,spec.ts}"
    TEST_DESC="All certificate tests"
    ;;
  *)
    echo -e "${RED}Unknown test type: $TEST_TYPE${NC}"
    echo "Valid test types: basic, journey, cert, cert-gen, all"
    exit 1
    ;;
esac

# Show test configuration
echo -e "${YELLOW}Test configuration:${NC}"
echo -e "${YELLOW}* Test type: $TEST_DESC${NC}"
echo -e "${YELLOW}* Test file: $TEST_FILE${NC}"

if [ -n "$UI_MODE" ]; then
  echo -e "${YELLOW}* UI mode: Headed (browser visible)${NC}"
else
  echo -e "${YELLOW}* UI mode: Headless (browser hidden)${NC}"
fi

if [ -n "$DEBUG_MODE" ]; then
  echo -e "${YELLOW}* Debug mode: Enabled${NC}"
else
  echo -e "${YELLOW}* Debug mode: Disabled${NC}"
fi

if [ -n "$UI_INSPECTOR" ]; then
  echo -e "${YELLOW}* UI Inspector: Enabled${NC}"
else
  echo -e "${YELLOW}* UI Inspector: Disabled${NC}"
fi

# Run the test
echo -e "\n${YELLOW}Running tests...${NC}"
echo -e "${YELLOW}$ npx playwright test $TEST_FILE $UI_MODE $DEBUG_MODE $UI_INSPECTOR${NC}"

# Start the test
npx playwright test $TEST_FILE $UI_MODE $DEBUG_MODE $UI_INSPECTOR

# Check test result
TEST_RESULT=$?
if [ $TEST_RESULT -eq 0 ]; then
  echo -e "${GREEN}✓ Tests completed successfully!${NC}"
else
  echo -e "${RED}✗ Tests failed with exit code $TEST_RESULT${NC}"
fi

# Show report location
echo -e "${YELLOW}Test artifacts are available in the test-results directory${NC}"
echo -e "${YELLOW}To view HTML report, run: npx playwright show-report${NC}"

exit $TEST_RESULT