#!/bin/bash

# Add a peer record. Caller provides name + kind + a key=value config blob
# that's serialised into the config_json column.
#
# Usage:
#   peerAdd <name> <kind> [key1=val1] [key2=val2] ...
#
# Example (backup-channel — Phase 1/2):
#   peerAdd homelab backup-channel hostname=homelab.local loc_idx=1

peerAdd()
{
    local name="$1"; shift
    local kind="$1"; shift

    local nv; nv=$(peerValidateName "$name")
    if [[ "$nv" != "ok" ]]; then
        isError "Invalid peer name: $nv"
        return 1
    fi
    local kv; kv=$(peerValidateKind "$kind")
    if [[ "$kv" != "ok" ]]; then
        isError "Cannot use kind '$kind' yet: $kv"
        return 1
    fi

    # Already exists?
    local existing
    existing=$(sqlite3 "$(_peerDb)" "SELECT id FROM peers WHERE name='$(peerSqlEscape "$name")';" 2>/dev/null)
    if [[ -n "$existing" ]]; then
        isError "Peer '$name' already exists (id=$existing). Use 'peer update' or 'peer remove' first."
        return 1
    fi

    # Build the JSON blob from key=value args. We don't pull in jq; values are
    # JSON-escaped inline (only handles strings and bare numerics, which is
    # what the kind-specific schemas need today).
    local first=1
    local cfg='{'
    local kv_pair k v
    for kv_pair in "$@"; do
        k="${kv_pair%%=*}"
        v="${kv_pair#*=}"
        [[ -z "$k" || "$k" == "$kv_pair" ]] && continue   # not a key=value
        local rendered
        if [[ "$v" =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
            rendered="$v"
        else
            local esc="${v//\\/\\\\}"; esc="${esc//\"/\\\"}"
            rendered="\"$esc\""
        fi
        if (( first )); then cfg+="\"$k\":$rendered"; first=0
        else                 cfg+=",\"$k\":$rendered"; fi
    done
    cfg+='}'

    sqlite3 "$(_peerDb)" \
        "INSERT INTO peers (name, kind, config_json) VALUES ('$(peerSqlEscape "$name")', '$(peerSqlEscape "$kind")', '$(peerSqlEscape "$cfg")');" 2>/dev/null

    if [[ $? -eq 0 ]]; then
        isSuccessful "Peer '$name' added (kind=$kind)"
        # Refresh WebUI cache if the generator is loaded.
        declare -F webuiGeneratePeers >/dev/null 2>&1 && webuiGeneratePeers >/dev/null 2>&1 || true
        return 0
    else
        isError "Failed to insert peer '$name'"
        return 1
    fi
}
