#!/bin/bash

# Apply a batch of `CFG_KEY=VALUE` pairs joined by `|` (literal `|` in values
# encoded as `%7C`). Re-runs apps.json regen + startScan after.
configUpdateBatch()
{
    local encoded_pairs="$1"

    if [[ -z "$encoded_pairs" ]]; then
        isNotice "configUpdateBatch called with no changes — skipping update."
    fi

    isHeader "Applying configuration changes"

    local applied=0
    local failed=0

    IFS='|' read -ra pairs <<< "$encoded_pairs"
    for pair in "${pairs[@]}"; do
        [[ -z "$pair" ]] && continue
        if [[ "$pair" =~ ^(CFG_[A-Z0-9_]+)=(.*)$ ]]; then
            local key="${BASH_REMATCH[1]}"
            local value="${BASH_REMATCH[2]//%7C/|}"
            if updateConfigOption "$key" "$value"; then
                ((applied++))
            else
                ((failed++))
            fi
        else
            isNotice "Skipping malformed pair: $pair"
            ((failed++))
        fi
    done

    isSuccessful "Applied $applied config change(s); $failed skipped/failed."

    echo ""
    echo "---- Regenerating apps.json from updated config..."
    echo ""
    if declare -f webuiGenerateLibrePortalConfig >/dev/null 2>&1; then
        webuiGenerateLibrePortalConfig >/dev/null 2>&1 || true
        isSuccessful "apps.json regenerated."
    fi

    echo ""
    echo "---- Running system scan to apply new configuration..."
    echo ""
    if declare -f startScan >/dev/null 2>&1; then
        startScan
        isSuccessful "System scan completed."
    fi

    echo ""
    isSuccessful "Configuration update complete."
}
