#!/bin/bash

# Get absolute path to this script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Navigate to wordpress-dev directory
cd "$(dirname "$SCRIPT_DIR")" || exit 1

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

source "$ENV_FILE"

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

echo "=== Checking Test Data on Staging Server ==="
echo "Remote host: $UPSKILL_STAGING_IP"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "==============================="

# Get test_trainer user ID
echo -e "\n${YELLOW}Getting test_trainer user ID...${NC}"
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"

# Check events created by test_trainer
echo -e "\n${YELLOW}Events created by test_trainer:${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp post list --post_type=tribe_events --author=\$(wp user get test_trainer --field=ID --allow-root) --fields=ID,post_title,post_status,post_author --format=table --allow-root"

# Check all events
echo -e "\n${YELLOW}All events in the system:${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp post list --post_type=tribe_events --fields=ID,post_title,post_status,post_author --format=table --number=20 --allow-root"

# Check event meta data
echo -e "\n${YELLOW}Checking event meta data for a sample event:${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp post meta list \$(wp post list --post_type=tribe_events --field=ID --number=1 --orderby=ID --order=DESC --allow-root) --fields=meta_key,meta_value --format=table --allow-root | grep -E '_Event|Cost'"

# Check ticket/attendee data
echo -e "\n${YELLOW}Checking for ticket data:${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp post list --post_type=tribe_tpp_attendees --fields=ID,post_title,post_status --format=table --number=10 --allow-root"

# Check roles and capabilities
echo -e "\n${YELLOW}Checking test_trainer roles and capabilities:${NC}"
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=roles --allow-root"

echo -e "\n${GREEN}Data check completed!${NC}"