# Canonical internal TiCDC metadata helpers.
# Requires: clinic-auth.sh.

_clinic_ticdc_positive_id() {
    local value="$1"
    local label="$2"

    case "$value" in
        ''|*[!0-9]*|0)
            echo "$label must be a positive unsigned integer" >&2
            return 2
            ;;
    esac
}

clinic_ticdc_changefeeds_list() {
    if [ $# -ne 2 ]; then
        echo "usage: clinic_ticdc_changefeeds_list <org_id> <cluster_id>" >&2
        return 2
    fi

    local org_id="$1"
    local cluster_id="$2"
    _clinic_ticdc_positive_id "$org_id" "org_id" || return $?
    _clinic_ticdc_positive_id "$cluster_id" "cluster_id" || return $?
    _ensure_clinic_auth || return 1

    curl -sS --fail-with-body \
        -H "Accept: application/json" \
        -H "Authorization: Bearer ${CLINIC_API_KEY}" \
        "${CLINIC_ENDPOINT}/data-proxy/api/v1/orgs/${org_id}/clusters/${cluster_id}/ticdc/changefeeds"
}

clinic_ticdc_changefeed_get() {
    if [ $# -ne 3 ]; then
        echo "usage: clinic_ticdc_changefeed_get <org_id> <cluster_id> <kernel_changefeed_id>" >&2
        return 2
    fi

    local org_id="$1"
    local cluster_id="$2"
    local changefeed_id="$3"
    _clinic_ticdc_positive_id "$org_id" "org_id" || return $?
    _clinic_ticdc_positive_id "$cluster_id" "cluster_id" || return $?
    _clinic_ticdc_positive_id "$changefeed_id" "kernel_changefeed_id" || return $?
    _ensure_clinic_auth || return 1

    curl -sS --fail-with-body \
        -H "Accept: application/json" \
        -H "Authorization: Bearer ${CLINIC_API_KEY}" \
        "${CLINIC_ENDPOINT}/data-proxy/api/v1/orgs/${org_id}/clusters/${cluster_id}/ticdc/changefeeds/${changefeed_id}"
}
