#!/bin/bash
# nocodb-api.sh - NocoDB 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"

NOCO_URL="http://192.168.25.5:8080"
NOCO_TOKEN=$(vault_nocodb_token)
NOCO_TABLE_ID=$(vault_nocodb_table_id)

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

# Make NocoDB API calls
nocodb_api() {
    local method="${1:-GET}"
    local endpoint="$2"
    local payload="${3:-}"
    
    local headers=(-H "xc-token: ${NOCO_TOKEN}" -H "Content-Type: application/json")
    
    if [ "$method" = "GET" ]; then
        curl -sk "${headers[@]}" "${NOCO_URL}${endpoint}"
    else
        curl -sk -X "$method" "${headers[@]}" -d "$payload" "${NOCO_URL}${endpoint}"
    fi
}

# Common operations
nocodb_get_leads() {
    nocodb_api GET "/api/v1/db/data/noco/Sales/${NOCO_TABLE_ID}"
}

nocodb_get_tables() {
    nocodb_api GET "/api/v2/meta/bases"
}

# Export
export -f nocodb_api nocodb_get_leads nocodb_get_tables
export NOCO_URL NOCO_TOKEN NOCO_TABLE_ID
