#!/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'

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

echo "=== Creating Test User on Staging Server ==="
echo "Remote host: $UPSKILL_STAGING_IP (upskill-staging.measurequick.com)"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "WordPress path: $UPSKILL_STAGING_PATH"
echo "==============================="

# Create test_trainer user
echo -e "\n${YELLOW}Creating test_trainer user...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp user create ${TEST_USER_USERNAME:-test_trainer} ${TEST_USER_EMAIL:-test@example.com} --role=${TEST_USER_ROLE:-hvac_trainer} --user_pass='${TEST_USER_PASSWORD:-Test123!}' --allow-root"

USER_CREATION_STATUS=$?
if [ $USER_CREATION_STATUS -eq 0 ]; then
    echo -e "${GREEN}✓ Test user 'test_trainer' created successfully${NC}"
else
    # Check if the user already exists
    echo -e "\n${YELLOW}Checking if user already exists...${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 --allow-root"
    
    if [ $? -eq 0 ]; then
        echo -e "${YELLOW}User 'test_trainer' already exists. Updating password...${NC}"
        sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
        "cd ${UPSKILL_STAGING_PATH} && wp user update test_trainer --user_pass='Test123!' --role=hvac_trainer --allow-root"
        check_status "User 'test_trainer' password updated"
    else
        echo -e "${RED}✗ Failed to create test user 'test_trainer'${NC}"
        exit 1
    fi
fi

# --- Diagnostic: Confirm Role Assignment ---
echo -e "\n${YELLOW}Verifying role assignment for 'test_trainer'...${NC}"
USER_ROLE=$(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")
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ User 'test_trainer' has roles: $USER_ROLE${NC}"
else
    echo -e "${RED}✗ Failed to retrieve roles for user 'test_trainer'${NC}"
fi

echo -e "\n${GREEN}Test user setup completed!${NC}"
echo "User: test_trainer"
echo "Password: Test123!"
echo "Role(s): $USER_ROLE"