# Canonical internal TiCDC metadata helpers.
# Requires: clinic-auth.sh and clinic-cluster.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_get() {
    local url="$1"
    local response_file http_status curl_status

    response_file=$(mktemp "${TMPDIR:-/tmp}/clinic-ticdc-response.XXXXXX") || return 1
    if http_status=$(curl -sS \
        -o "$response_file" \
        -w "%{http_code}" \
        -H "Accept: application/json" \
        -H "Authorization: Bearer ${CLINIC_API_KEY}" \
        "$url"); then
        curl_status=0
    else
        curl_status=$?
    fi

    command cat "$response_file"
    command rm -f -- "$response_file"

    if [ "$curl_status" -ne 0 ]; then
        return "$curl_status"
    fi
    case "$http_status" in
        2??) return 0 ;;
        *) return 22 ;;
    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

    _clinic_ticdc_get \
        "${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"
    local encoded_changefeed_id
    _clinic_ticdc_positive_id "$org_id" "org_id" || return $?
    _clinic_ticdc_positive_id "$cluster_id" "cluster_id" || return $?
    if [ -z "$changefeed_id" ]; then
        echo "kernel_changefeed_id must not be empty" >&2
        return 2
    fi
    _ensure_clinic_auth || return 1
    encoded_changefeed_id=$(_clinic_path_segment "$changefeed_id") || return 1

    _clinic_ticdc_get \
        "${CLINIC_ENDPOINT}/data-proxy/api/v1/orgs/${org_id}/clusters/${cluster_id}/ticdc/changefeeds/${encoded_changefeed_id}"
}
