#!/bin/bash

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

source .env

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

# Default values
SKIP_CONFIRM=false

# 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
}

# Function to show usage
show_usage() {
    echo "Usage: $0 {backup|restore <backup_file>|reset|generate-test-data [type]|cleanup-test-data}"
    echo ""
    echo "Commands:"
    echo "  backup              Create a backup of the development database"
    echo "  restore FILE        Restore database from a backup file"
    echo "  reset              Reset the development database"
    echo "  generate-test-data  Generate test data (default: basic)"
    echo "  cleanup-test-data   Remove all test data"
    echo ""
    echo "Test Data Types:"
    echo "  basic              Basic test data (1 trainer, 1 event)"
    echo "  extended           Extended test data (multiple trainers, events)"
    echo "  stress            Large dataset for stress testing"
    echo ""
    echo "Options:"
    echo "  -y, --yes         Skip confirmation prompts"
    echo "  -h, --help        Show this help message"
}

# Function to backup development database
backup_dev_db() {
    local backup_file="backups/dev_db_$(date +%Y%m%d_%H%M%S).sql"
    mkdir -p backups
    
    echo "Backing up development database..."
    docker-compose exec -T db mysqldump -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" "$DEV_DB_NAME" > "$backup_file"
    check_status "Database backup" || exit 1
    echo "Backup saved to: $backup_file"
}

# Function to restore development database
restore_dev_db() {
    local backup_file=$1
    if [ ! -f "$backup_file" ]; then
        echo -e "${RED}Error: Backup file not found: $backup_file${NC}"
        exit 1
    fi
    
    echo "Restoring development database..."
    cat "$backup_file" | docker-compose exec -T db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" "$DEV_DB_NAME"
    check_status "Database restore" || exit 1
}

# Function to reset development database
reset_dev_db() {
    echo "Resetting development database..."
    docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" -e "DROP DATABASE IF EXISTS $DEV_DB_NAME; CREATE DATABASE $DEV_DB_NAME;"
    check_status "Database reset" || exit 1
}

# Function to generate test data
generate_test_data() {
    local data_type=${1:-"basic"}
    
    echo "Generating ${data_type} test data..."
    
    # Create test users based on data type
    case "$data_type" in
        basic)
            echo "Creating basic test data..."
            # Create test trainer
            docker-compose exec wordpress wp user create test_trainer test.trainer@example.com \
                --role=author --user_pass=SecurePass123! --allow-root
            check_status "Test trainer creation"
            
            # Create test event
            EVENT_ID=$(docker-compose exec wordpress wp post create \
                --post_type=tribe_events \
                --post_title="Test HVAC Training Event" \
                --post_content="This is a test training event for HVAC professionals." \
                --post_status=publish \
                --post_author=test_trainer \
                --porcelain \
                --allow-root)
            check_status "Test event creation"
            
            # Set event metadata
            docker-compose exec wordpress wp post meta update $EVENT_ID _EventStartDate "$(date -v+1d '+%Y-%m-%d 10:00:00')" --allow-root
            docker-compose exec wordpress wp post meta update $EVENT_ID _EventEndDate "$(date -v+1d '+%Y-%m-%d 16:00:00')" --allow-root
            docker-compose exec wordpress wp post meta update $EVENT_ID _EventVenueID "1" --allow-root
            check_status "Event metadata setup"
            
            # Create test ticket
            docker-compose exec wordpress wp post create \
                --post_type=tribe_rsvp \
                --post_title="Standard Ticket" \
                --post_parent=$EVENT_ID \
                --post_status=publish \
                --meta_input='{"_price": "99.99", "_stock": "50"}' \
                --allow-root
            check_status "Test ticket creation"
            ;;
            
        extended)
            echo "Creating extended test data..."
            # Create multiple trainers
            for i in {1..3}; do
                docker-compose exec wordpress wp user create "trainer_${i}" "trainer${i}@example.com" \
                    --role=author --user_pass=SecurePass123! --allow-root
                check_status "Trainer ${i} creation"
                
                # Create multiple events for each trainer
                for j in {1..3}; do
                    EVENT_ID=$(docker-compose exec wordpress wp post create \
                        --post_type=tribe_events \
                        --post_title="HVAC Training ${i}-${j}" \
                        --post_content="Extended test training event ${j} by trainer ${i}." \
                        --post_status=publish \
                        --post_author="trainer_${i}" \
                        --porcelain \
                        --allow-root)
                    
                    # Set event metadata with different dates
                    START_DATE=$(date -v+${j}d '+%Y-%m-%d 10:00:00')
                    END_DATE=$(date -v+${j}d '+%Y-%m-%d 16:00:00')
                    docker-compose exec wordpress wp post meta update $EVENT_ID _EventStartDate "$START_DATE" --allow-root
                    docker-compose exec wordpress wp post meta update $EVENT_ID _EventEndDate "$END_DATE" --allow-root
                    docker-compose exec wordpress wp post meta update $EVENT_ID _EventVenueID "$j" --allow-root
                    
                    # Create tickets with different prices
                    docker-compose exec wordpress wp post create \
                        --post_type=tribe_rsvp \
                        --post_title="Early Bird Ticket" \
                        --post_parent=$EVENT_ID \
                        --post_status=publish \
                        --meta_input="{\"_price\": \"79.99\", \"_stock\": \"20\"}" \
                        --allow-root
                        
                    docker-compose exec wordpress wp post create \
                        --post_type=tribe_rsvp \
                        --post_title="Regular Ticket" \
                        --post_parent=$EVENT_ID \
                        --post_status=publish \
                        --meta_input="{\"_price\": \"99.99\", \"_stock\": \"30\"}" \
                        --allow-root
                done
            done
            ;;
            
        stress)
            echo "Creating stress test data..."
            # Create many trainers and events for load testing
            for i in {1..10}; do
                docker-compose exec wordpress wp user create "stress_trainer_${i}" "stress${i}@example.com" \
                    --role=author --user_pass=SecurePass123! --allow-root
                
                # Create many events per trainer
                for j in {1..10}; do
                    EVENT_ID=$(docker-compose exec wordpress wp post create \
                        --post_type=tribe_events \
                        --post_title="Stress Test Event ${i}-${j}" \
                        --post_content="Stress test training event ${j} by trainer ${i}." \
                        --post_status=publish \
                        --post_author="stress_trainer_${i}" \
                        --porcelain \
                        --allow-root)
                    
                    START_DATE=$(date -v+${j}d '+%Y-%m-%d 10:00:00')
                    END_DATE=$(date -v+${j}d '+%Y-%m-%d 16:00:00')
                    docker-compose exec wordpress wp post meta update $EVENT_ID _EventStartDate "$START_DATE" --allow-root
                    docker-compose exec wordpress wp post meta update $EVENT_ID _EventEndDate "$END_DATE" --allow-root
                    docker-compose exec wordpress wp post meta update $EVENT_ID _EventVenueID "1" --allow-root
                    
                    # Create multiple ticket types
                    for k in {1..3}; do
                        docker-compose exec wordpress wp post create \
                            --post_type=tribe_rsvp \
                            --post_title="Ticket Type ${k}" \
                            --post_parent=$EVENT_ID \
                            --post_status=publish \
                            --meta_input="{\"_price\": \"${k}9.99\", \"_stock\": \"${k}0\"}" \
                            --allow-root
                    done
                done
            done
            ;;
            
        *)
            echo -e "${RED}Error: Invalid test data type. Use 'basic', 'extended', or 'stress'${NC}"
            exit 1
            ;;
    esac
    
    echo -e "${GREEN}Test data generation completed!${NC}"
}

# Function to cleanup test data
cleanup_test_data() {
    echo "Cleaning up test data..."
    
    # Remove test events
    docker-compose exec wordpress wp post delete $(docker-compose exec wordpress wp post list --post_type=tribe_events --format=ids --allow-root) --force --allow-root
    check_status "Event cleanup"
    
    # Remove test tickets
    docker-compose exec wordpress wp post delete $(docker-compose exec wordpress wp post list --post_type=tribe_rsvp --format=ids --allow-root) --force --allow-root
    check_status "Ticket cleanup"
    
    # Remove test users
    docker-compose exec wordpress wp user delete $(docker-compose exec wordpress wp user list --role=author --format=ids --allow-root) --yes --allow-root
    check_status "User cleanup"
    
    echo -e "${GREEN}Test data cleanup completed!${NC}"
}

# Function to confirm action
confirm_action() {
    if [ "$SKIP_CONFIRM" = true ]; then
        return 0
    fi
    
    read -p "$1 [y/N] " -n 1 -r
    echo
    [[ $REPLY =~ ^[Yy]$ ]]
}

# Parse command line options
while [[ $# -gt 0 ]]; do
    case "$1" in
        backup)
            backup_dev_db
            exit 0
            ;;
        restore)
            if [ -z "$2" ]; then
                echo "Error: Please specify backup file to restore"
                show_usage
                exit 1
            fi
            restore_dev_db "$2"
            exit 0
            ;;
        reset)
            if confirm_action "${YELLOW}Warning: This will delete all data in the development database. Continue?${NC}"; then
                reset_dev_db
            fi
            exit 0
            ;;
        generate-test-data)
            shift
            data_type=${1:-"basic"}
            if confirm_action "Generate ${data_type} test data?"; then
                generate_test_data "$data_type"
            fi
            exit 0
            ;;
        cleanup-test-data)
            if confirm_action "${YELLOW}Warning: This will remove all test data. Continue?${NC}"; then
                cleanup_test_data
            fi
            exit 0
            ;;
        -y|--yes)
            SKIP_CONFIRM=true
            shift
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        *)
            echo "Error: Unknown command '$1'"
            show_usage
            exit 1
            ;;
    esac
done

# Show usage if no command provided
show_usage
exit 1