#!/bin/bash

# Create Task File Function
# Creates a task file and adds it to the task queue for the task processor

createTaskFile() {
    local command="$1"
    local task_type="$2"
    local app_name="$3"

    # Safeguarding
    if [ -z "$command" ]; then
        isNotice "Empty command provided to createTaskFile"
    fi

    # Set task directory
    local task_dir="${containers_dir}libreportal/frontend/data/tasks"

    # Ensure task directory exists
    if [ ! -d "$task_dir" ]; then
        mkdir -p "$task_dir"
        chown -R $docker_install_user:$docker_install_user "$task_dir"
    fi

    # Ensure queue.json exists
    if [ ! -f "$task_dir/queue.json" ]; then
        echo "[]" | tee "$task_dir/queue.json" >/dev/null
        chown $docker_install_user:$docker_install_user "$task_dir/queue.json"
    fi

    # Generate unique task ID
    local task_id="task_$(date +%s)_$(openssl rand -hex 4 2>/dev/null || echo $RANDOM)"

    # Create task file
    local task_file="$task_dir/${task_id}.json"
    local created_at=$(date -Iseconds 2>/dev/null || date '+%Y-%m-%dT%H:%M:%S')

    # Build task JSON
    local task_json="{"
    task_json+="\"id\": \"$task_id\","
    task_json+="\"command\": \"$command\","
    task_json+="\"status\": \"queued\","
    task_json+="\"created_at\": \"$created_at\""

    # Add optional fields if provided
    if [ -n "$task_type" ]; then
        task_json+=","
        task_json+="\"type\": \"$task_type\""
    fi

    if [ -n "$app_name" ]; then
        task_json+=","
        task_json+="\"app\": \"$app_name\""
    fi

    task_json+="}"

    # Write task file
    echo "$task_json" | tee "$task_file" >/dev/null
    chown $docker_install_user:$docker_install_user "$task_file"

    # Add task ID to queue.json
    local queue_content=$(cat "$task_dir/queue.json" 2>/dev/null)
    
    if command -v jq >/dev/null 2>&1; then
        # Use jq if available
        echo "$queue_content" | jq --arg task "$task_id" '. + [$task]' | tee "$task_dir/queue.json" >/dev/null
    else
        # Fallback: manual JSON manipulation
        if [ "$queue_content" = "[]" ]; then
            echo "[\"$task_id\"]" | tee "$task_dir/queue.json" >/dev/null
        else
            echo "$queue_content" | sed 's/\]$/,\n"'$task_id'"]/' | tee "$task_dir/queue.json" >/dev/null
        fi
    fi

    chown $docker_install_user:$docker_install_user "$task_dir/queue.json"

    isSuccessful "Task created: $task_id"
}
