#!/bin/bash

################################################################################
# Standalone Shopify Order Deletion Script
# Strategy: Fetch All IDs -> Split -> Parallel Delete
# Optimized for reliable parallel processing without race conditions
################################################################################

# Shopify Configuration (hardcoded from .env)
SHOPIFY_SHOP_DOMAIN="yuqe0m-xr.myshopify.com"
SHOPIFY_ACCESS_TOKEN="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"
SHOPIFY_API_VERSION="2026-01"

# Script Configuration
WORKERS=25                    # Number of parallel processes
BATCH_SIZE=250                # Orders per GraphQL fetch (max 250 usually safe)
# LOG_DIR="storage/logs"
# TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
LOG_FILE="/var/www/magentomigration.zodiaconline.com/order_details_log"
DELETED_FILE="/var/www/magentomigration.zodiaconline.com/deleted_orders_numbers.txt"
TEMP_DIR="/tmp/order_deletion_$$"
ALL_ORDERS_FILE="${TEMP_DIR}/all_orders_to_delete.txt"

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

################################################################################
# Functions
################################################################################

log_message() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}

log_error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1" | tee -a "$LOG_FILE"
}

setup() {
    log_message "Setting up deletion process..."
    
    # Create temp directory
    mkdir -p "$TEMP_DIR"
    mkdir -p "$LOG_DIR"
    
    # Initialize counters
    echo "0" > "${TEMP_DIR}/total_deleted.txt"
    
    log_message "Setup completed. Temp dir: $TEMP_DIR"
}

fetch_all_orders() {
    log_message "Step 1: Fetching first 500 orders (NO FILTERS)..."
    
    local has_next_page=true
    local current_cursor=""
    local total_fetched=0
    
    while [ "$has_next_page" = "true" ]; do
        # GraphQL query to get just ID and Name
        local query='query ($cursor: String) {
            orders(first: '$BATCH_SIZE', after: $cursor, query: "status:any") {
                edges {
                    node {
                        id
                        name
                        createdAt
                    }
                }
                pageInfo {
                    hasNextPage
                    endCursor
                }
            }
        }'
        
        # Escape quotes for JSON
        local escaped_query=$(echo "$query" | sed 's/"/\\"/g' | tr -d '\n')
        
        # Make API request
        local response=$(curl -s -X POST \
            "https://${SHOPIFY_SHOP_DOMAIN}/admin/api/${SHOPIFY_API_VERSION}/graphql.json" \
            -H "X-Shopify-Access-Token: ${SHOPIFY_ACCESS_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"query\":\"$escaped_query\"$([ -n "$current_cursor" ] && echo ",\"variables\":{\"cursor\":\"$current_cursor\"}" || echo "")}")
            
        # DEBUG: Print first response to check for errors
        if [ "$total_fetched" -eq 0 ]; then
             echo "DEBUG: Raw Response: $response"
             echo "DEBUG: Query Used: $query"
        fi
            
        # Extract IDs and append to file
        # Format: ID|NAME
        echo "$response" | php -r "
            \$data = json_decode(file_get_contents('php://stdin'), true);
            if (isset(\$data['data']['orders']['edges'])) {
                foreach (\$data['data']['orders']['edges'] as \$edge) {
                    echo \$edge['node']['id'] . '|' . \$edge['node']['name'] . PHP_EOL;
                }
            }
        " >> "$ALL_ORDERS_FILE"
        
        # Get pagination info
        local page_info=$(echo "$response" | php -r "
            \$data = json_decode(file_get_contents('php://stdin'), true);
            echo (isset(\$data['data']['orders']['pageInfo']['hasNextPage']) && \$data['data']['orders']['pageInfo']['hasNextPage'] ? 'true' : 'false') . '|' . (\$data['data']['orders']['pageInfo']['endCursor'] ?? '');
        ")
        
        has_next_page=$(echo "$page_info" | cut -d'|' -f1)
        current_cursor=$(echo "$page_info" | cut -d'|' -f2)
        
        # Update progress
        local batch_count=$(grep -c . "$ALL_ORDERS_FILE")
        echo -ne "Fetching orders... Found: $batch_count\r"
        
        # Stop after fetching 500 orders
        if [ "$batch_count" -ge 500 ]; then
            log_message "Reached limit of 500 orders. Stopping fetch."
            # Truncate file to exactly 500 lines if we fetched more
            head -n 500 "$ALL_ORDERS_FILE" > "${ALL_ORDERS_FILE}.tmp" && mv "${ALL_ORDERS_FILE}.tmp" "$ALL_ORDERS_FILE"
            break
        fi
        
        # Rate limit protection
        sleep 0.2
    done
    
    echo ""
    local final_count=$(wc -l < "$ALL_ORDERS_FILE")
    log_message "Fetch complete. Total orders to delete: $final_count"
    
    if [ "$final_count" -eq 0 ]; then
        log_message "No orders found. Exiting."
        exit 0
    fi
}

split_workload() {
    log_message "Step 2: Splitting workload for $WORKERS workers..."
    
    # Split the main file into chunks
    # --numeric-suffixes starts at 00
    # --additional-suffix=.txt adds extension
    # -n l/N splits into N files based on lines
    split -n "l/$WORKERS" --numeric-suffixes=1 --additional-suffix=.txt "$ALL_ORDERS_FILE" "${TEMP_DIR}/chunk_"
    
    local chunk_count=$(ls "${TEMP_DIR}/chunk_"*.txt 2>/dev/null | wc -l)
    log_message "Created $chunk_count chunks."
}

delete_order_api() {
    local order_id=$1
    
    local mutation='mutation {
        orderDelete(orderId: "'$order_id'") {
            deletedId
            userErrors {
                field
                message
            }
        }
    }'
    
    local escaped_mutation=$(echo "$mutation" | sed 's/"/\\"/g' | tr -d '\n')

    curl -s -X POST \
        "https://${SHOPIFY_SHOP_DOMAIN}/admin/api/${SHOPIFY_API_VERSION}/graphql.json" \
        -H "X-Shopify-Access-Token: ${SHOPIFY_ACCESS_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{\"query\":\"$escaped_mutation\"}"
}

worker_process() {
    local chunk_file=$1
    local worker_id=$2
    
    if [ ! -f "$chunk_file" ]; then
        log_message "Worker #$worker_id: No work file found."
        return
    fi
    
    local total_lines=$(wc -l < "$chunk_file")
    log_message "Worker #$worker_id started. Processing $total_lines orders from $(basename "$chunk_file")"
    
    local current=0
    
    while IFS='|' read -r order_id order_name; do
        if [ -n "$order_id" ]; then
            current=$((current + 1))
            
            # Delete API Call
            local response=$(delete_order_api "$order_id")
            
            # DEBUG: Log response
            log_message "Delete response for $order_name: $response"

            # Check success: Must have a valid deletedId (starts with gid)
            if echo "$response" | grep -q '"deletedId":"gid'; then
                 echo "$order_name" >> "$DELETED_FILE"
                 
                 # Update consolidated counter every 10 orders to reduce lock contention
                 if (( current % 10 == 0 )); then
                     flock "${TEMP_DIR}/lock" -c "
                         count=\$(cat ${TEMP_DIR}/total_deleted.txt)
                         echo \$((count + 10)) > ${TEMP_DIR}/total_deleted.txt
                     "
                 fi
            else
                log_error "Worker #$worker_id: Failed to delete $order_name ($order_id). Response: $response"
            fi
            
            # Rate limit specific sleep per worker
            # 20 workers * 2 req/sec = 40 req/sec limit? Shopify Plus is 40pts/sec bucket.
            # Mutation costs 10 pts? orderDelete cost is usually quite high.
            # Actually, orderDelete cost depends. Usually 10.
            # 20 workers deleting might hit rate limits fast.
            # Sleep 1 second per delete to be safe.
            sleep 0.5
        fi
    done < "$chunk_file"
    
    # Flush remaining count
    local remainder=$((current % 10))
    if (( remainder > 0 )); then
        flock "${TEMP_DIR}/lock" -c "
            count=\$(cat ${TEMP_DIR}/total_deleted.txt)
            echo \$((count + remainder)) > ${TEMP_DIR}/total_deleted.txt
        "
    fi
    
    log_message "Worker #$worker_id finished."
}

start_workers() {
    log_message "Step 3: Launching workers..."
    
    local i=1
    for file in "${TEMP_DIR}/chunk_"*.txt; do
        worker_process "$file" "$i" &
        echo $! >> "${TEMP_DIR}/pids.txt"
        i=$((i + 1))
    done
    
    log_message "Workers launched."
}

monitor_progress() {
    log_message "Monitoring..."
    local total_to_delete=$(wc -l < "$ALL_ORDERS_FILE")
    
    while true; do
        local running=0
        if [ -f "${TEMP_DIR}/pids.txt" ]; then
            while read -r pid; do
                if ps -p "$pid" > /dev/null 2>&1; then
                    running=$((running + 1))
                fi
            done < "${TEMP_DIR}/pids.txt"
        fi
        
        local deleted=$(cat "${TEMP_DIR}/total_deleted.txt" 2>/dev/null || echo "0")
        local percent=$((deleted * 100 / total_to_delete))
        
        echo -ne "${BLUE}Running: $running | Deleted: $deleted / $total_to_delete ($percent%)${NC}\r"
        
        if [ $running -eq 0 ]; then
            echo ""
            break
        fi
        sleep 5
    done
    log_message "All workers finished."
}

cleanup() {
    if [ -d "$TEMP_DIR" ]; then
        # Kill pids if any are still running (ctrl+c case)
        if [ -f "${TEMP_DIR}/pids.txt" ]; then
             while read -r pid; do kill "$pid" 2>/dev/null; done < "${TEMP_DIR}/pids.txt"
        fi
        rm -rf "$TEMP_DIR"
    fi
}

################################################################################
# Main
################################################################################

trap cleanup EXIT INT TERM

echo "================================================"
echo "  Safe Parallel Order Deletion (< 2026-01-01)"
echo "================================================"

setup
fetch_all_orders
split_workload
start_workers
monitor_progress

echo "Done."
exit 0
