#!/bin/bash
# grist_api.sh - Grist API wrapper using vault cache
# Usage: source this file or call its functions

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/vault-env.sh"

GRIST_URL="https://grist.beawit.net"
GRIST_TOKEN=$(vaul…ken)

if [ -z "$GRIST_TOKEN" ]; then
    echo "Error: Could not retrieve Grist token from vault cache"
    return 1 2>/dev/null || exit 1
fi

# Function to make Grist API calls
grist_api() {
    local method="${1:-GET}"
    local endpoint="$2"
    local payload="${3:-}"
    
    local headers=(-H "Authorization: Bearer ${GRIST_TOKEN}" -H "Content-Type: application/json")
    
    if [ "$method" = "GET" ]; then
        curl -sk "${headers[@]}" "${GRIST_URL}${endpoint}"
    else
        curl -sk -X "$method" "${headers[@]}" -d "$payload" "${GRIST_URL}${endpoint}"
    fi
}

# Export
export -f grist_api
export GRIST_URL GRIST_TOKEN
