// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Code generated by protoc-gen-go_gapic. DO NOT EDIT.

package bigquery

import (
	"bytes"
	"context"
	"fmt"
	"log/slog"
	"math"
	"net/http"
	"net/url"
	"time"

	bigquerypb "cloud.google.com/go/bigquery/v2/apiv2/bigquerypb"
	gax "github.com/googleapis/gax-go/v2"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	"google.golang.org/api/option/internaloption"
	gtransport "google.golang.org/api/transport/grpc"
	httptransport "google.golang.org/api/transport/http"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

var newJobClientHook clientHook

// JobCallOptions contains the retry settings for each method of JobClient.
type JobCallOptions struct {
	CancelJob       []gax.CallOption
	GetJob          []gax.CallOption
	InsertJob       []gax.CallOption
	DeleteJob       []gax.CallOption
	ListJobs        []gax.CallOption
	GetQueryResults []gax.CallOption
	Query           []gax.CallOption
}

func defaultJobGRPCClientOptions() []option.ClientOption {
	return []option.ClientOption{
		internaloption.WithDefaultEndpoint("bigquery.googleapis.com:443"),
		internaloption.WithDefaultEndpointTemplate("bigquery.UNIVERSE_DOMAIN:443"),
		internaloption.WithDefaultMTLSEndpoint("bigquery.mtls.googleapis.com:443"),
		internaloption.WithDefaultUniverseDomain("googleapis.com"),
		internaloption.WithDefaultAudience("https://bigquery.googleapis.com/"),
		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
		internaloption.EnableJwtWithScope(),
		internaloption.EnableNewAuthLibrary(),
		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
	}
}

func defaultJobCallOptions() *JobCallOptions {
	return &JobCallOptions{
		CancelJob: []gax.CallOption{
			gax.WithTimeout(64000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		GetJob: []gax.CallOption{
			gax.WithTimeout(64000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		InsertJob: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				})
			}),
		},
		DeleteJob: []gax.CallOption{
			gax.WithTimeout(64000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		ListJobs: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				})
			}),
		},
		GetQueryResults: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				})
			}),
		},
		Query: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.DeadlineExceeded,
					codes.Unavailable,
					codes.ResourceExhausted,
				}, gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				})
			}),
		},
	}
}

func defaultJobRESTCallOptions() *JobCallOptions {
	return &JobCallOptions{
		CancelJob: []gax.CallOption{
			gax.WithTimeout(64000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
		GetJob: []gax.CallOption{
			gax.WithTimeout(64000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
		InsertJob: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
		DeleteJob: []gax.CallOption{
			gax.WithTimeout(64000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
		ListJobs: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
		GetQueryResults: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
		Query: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnHTTPCodes(gax.Backoff{
					Initial:    400 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 2.00,
				},
					http.StatusGatewayTimeout,
					http.StatusServiceUnavailable,
					http.StatusTooManyRequests)
			}),
		},
	}
}

// internalJobClient is an interface that defines the methods available from BigQuery API.
type internalJobClient interface {
	Close() error
	setGoogleClientInfo(...string)
	Connection() *grpc.ClientConn
	CancelJob(context.Context, *bigquerypb.CancelJobRequest, ...gax.CallOption) (*bigquerypb.JobCancelResponse, error)
	GetJob(context.Context, *bigquerypb.GetJobRequest, ...gax.CallOption) (*bigquerypb.Job, error)
	InsertJob(context.Context, *bigquerypb.InsertJobRequest, ...gax.CallOption) (*bigquerypb.Job, error)
	DeleteJob(context.Context, *bigquerypb.DeleteJobRequest, ...gax.CallOption) error
	ListJobs(context.Context, *bigquerypb.ListJobsRequest, ...gax.CallOption) *ListFormatJobIterator
	GetQueryResults(context.Context, *bigquerypb.GetQueryResultsRequest, ...gax.CallOption) (*bigquerypb.GetQueryResultsResponse, error)
	Query(context.Context, *bigquerypb.PostQueryRequest, ...gax.CallOption) (*bigquerypb.QueryResponse, error)
}

// JobClient is a client for interacting with BigQuery API.
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type JobClient struct {
	// The internal transport-dependent client.
	internalClient internalJobClient

	// The call options for this service.
	CallOptions *JobCallOptions
}

// Wrapper methods routed to the internal client.

// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *JobClient) Close() error {
	return c.internalClient.Close()
}

// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *JobClient) setGoogleClientInfo(keyval ...string) {
	c.internalClient.setGoogleClientInfo(keyval...)
}

// Connection returns a connection to the API service.
//
// Deprecated: Connections are now pooled so this method does not always
// return the same resource.
func (c *JobClient) Connection() *grpc.ClientConn {
	return c.internalClient.Connection()
}

// CancelJob requests that a job be cancelled. This call will return immediately, and
// the client will need to poll for the job status to see if the cancel
// completed successfully. Cancelled jobs may still incur costs.
func (c *JobClient) CancelJob(ctx context.Context, req *bigquerypb.CancelJobRequest, opts ...gax.CallOption) (*bigquerypb.JobCancelResponse, error) {
	return c.internalClient.CancelJob(ctx, req, opts...)
}

// GetJob returns information about a specific job. Job information is available for
// a six month period after creation. Requires that you’re the person who ran
// the job, or have the Is Owner project role.
func (c *JobClient) GetJob(ctx context.Context, req *bigquerypb.GetJobRequest, opts ...gax.CallOption) (*bigquerypb.Job, error) {
	return c.internalClient.GetJob(ctx, req, opts...)
}

// InsertJob starts a new asynchronous job.
//
// This API has two different kinds of endpoint URIs, as this method supports
// a variety of use cases.
//
//	The Metadata URI is used for most interactions, as it accepts the job
//	configuration directly.
//
//	The Upload URI is ONLY for the case when you’re sending both a load job
//	configuration and a data stream together.  In this case, the Upload URI
//	accepts the job configuration and the data as two distinct multipart MIME
//	parts.
func (c *JobClient) InsertJob(ctx context.Context, req *bigquerypb.InsertJobRequest, opts ...gax.CallOption) (*bigquerypb.Job, error) {
	return c.internalClient.InsertJob(ctx, req, opts...)
}

// DeleteJob requests the deletion of the metadata of a job. This call returns when the
// job’s metadata is deleted.
func (c *JobClient) DeleteJob(ctx context.Context, req *bigquerypb.DeleteJobRequest, opts ...gax.CallOption) error {
	return c.internalClient.DeleteJob(ctx, req, opts...)
}

// ListJobs lists all jobs that you started in the specified project. Job information
// is available for a six month period after creation. The job list is sorted
// in reverse chronological order, by job creation time. Requires the Can View
// project role, or the Is Owner project role if you set the allUsers
// property.
func (c *JobClient) ListJobs(ctx context.Context, req *bigquerypb.ListJobsRequest, opts ...gax.CallOption) *ListFormatJobIterator {
	return c.internalClient.ListJobs(ctx, req, opts...)
}

// GetQueryResults rPC to get the results of a query job.
func (c *JobClient) GetQueryResults(ctx context.Context, req *bigquerypb.GetQueryResultsRequest, opts ...gax.CallOption) (*bigquerypb.GetQueryResultsResponse, error) {
	return c.internalClient.GetQueryResults(ctx, req, opts...)
}

// Query runs a BigQuery SQL query synchronously and returns query results if the
// query completes within a specified timeout.
func (c *JobClient) Query(ctx context.Context, req *bigquerypb.PostQueryRequest, opts ...gax.CallOption) (*bigquerypb.QueryResponse, error) {
	return c.internalClient.Query(ctx, req, opts...)
}

// jobGRPCClient is a client for interacting with BigQuery API over gRPC transport.
//
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type jobGRPCClient struct {
	// Connection pool of gRPC connections to the service.
	connPool gtransport.ConnPool

	// Points back to the CallOptions field of the containing JobClient
	CallOptions **JobCallOptions

	// The gRPC API client.
	jobClient bigquerypb.JobServiceClient

	// The x-goog-* metadata to be sent with each request.
	xGoogHeaders []string

	logger *slog.Logger
}

// NewJobClient creates a new job service client based on gRPC.
// The returned client must be Closed when it is done being used to clean up its underlying connections.
func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, error) {
	clientOpts := defaultJobGRPCClientOptions()
	if newJobClientHook != nil {
		hookOpts, err := newJobClientHook(ctx, clientHookParams{})
		if err != nil {
			return nil, err
		}
		clientOpts = append(clientOpts, hookOpts...)
	}

	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
	if err != nil {
		return nil, err
	}
	client := JobClient{CallOptions: defaultJobCallOptions()}

	c := &jobGRPCClient{
		connPool:    connPool,
		jobClient:   bigquerypb.NewJobServiceClient(connPool),
		CallOptions: &client.CallOptions,
		logger:      internaloption.GetLogger(opts),
	}
	c.setGoogleClientInfo()

	client.internalClient = c

	return &client, nil
}

// Connection returns a connection to the API service.
//
// Deprecated: Connections are now pooled so this method does not always
// return the same resource.
func (c *jobGRPCClient) Connection() *grpc.ClientConn {
	return c.connPool.Conn()
}

// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *jobGRPCClient) setGoogleClientInfo(keyval ...string) {
	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version, "pb", protoVersion)
	c.xGoogHeaders = []string{
		"x-goog-api-client", gax.XGoogHeader(kv...),
	}
}

// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *jobGRPCClient) Close() error {
	return c.connPool.Close()
}

// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type jobRESTClient struct {
	// The http endpoint to connect to.
	endpoint string

	// The http client.
	httpClient *http.Client

	// The x-goog-* headers to be sent with each request.
	xGoogHeaders []string

	// Points back to the CallOptions field of the containing JobClient
	CallOptions **JobCallOptions

	logger *slog.Logger
}

// NewJobRESTClient creates a new job service rest client.
func NewJobRESTClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, error) {
	clientOpts := append(defaultJobRESTClientOptions(), opts...)
	httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
	if err != nil {
		return nil, err
	}

	callOpts := defaultJobRESTCallOptions()
	c := &jobRESTClient{
		endpoint:    endpoint,
		httpClient:  httpClient,
		CallOptions: &callOpts,
		logger:      internaloption.GetLogger(opts),
	}
	c.setGoogleClientInfo()

	return &JobClient{internalClient: c, CallOptions: callOpts}, nil
}

func defaultJobRESTClientOptions() []option.ClientOption {
	return []option.ClientOption{
		internaloption.WithDefaultEndpoint("https://bigquery.googleapis.com"),
		internaloption.WithDefaultEndpointTemplate("https://bigquery.UNIVERSE_DOMAIN"),
		internaloption.WithDefaultMTLSEndpoint("https://bigquery.mtls.googleapis.com"),
		internaloption.WithDefaultUniverseDomain("googleapis.com"),
		internaloption.WithDefaultAudience("https://bigquery.googleapis.com/"),
		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
		internaloption.EnableNewAuthLibrary(),
	}
}

// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *jobRESTClient) setGoogleClientInfo(keyval ...string) {
	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN", "pb", protoVersion)
	c.xGoogHeaders = []string{
		"x-goog-api-client", gax.XGoogHeader(kv...),
	}
}

// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *jobRESTClient) Close() error {
	// Replace httpClient with nil to force cleanup.
	c.httpClient = nil
	return nil
}

// Connection returns a connection to the API service.
//
// Deprecated: This method always returns nil.
func (c *jobRESTClient) Connection() *grpc.ClientConn {
	return nil
}
func (c *jobGRPCClient) CancelJob(ctx context.Context, req *bigquerypb.CancelJobRequest, opts ...gax.CallOption) (*bigquerypb.JobCancelResponse, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).CancelJob[0:len((*c.CallOptions).CancelJob):len((*c.CallOptions).CancelJob)], opts...)
	var resp *bigquerypb.JobCancelResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.jobClient.CancelJob, req, settings.GRPC, c.logger, "CancelJob")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *jobGRPCClient) GetJob(ctx context.Context, req *bigquerypb.GetJobRequest, opts ...gax.CallOption) (*bigquerypb.Job, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...)
	var resp *bigquerypb.Job
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.jobClient.GetJob, req, settings.GRPC, c.logger, "GetJob")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *jobGRPCClient) InsertJob(ctx context.Context, req *bigquerypb.InsertJobRequest, opts ...gax.CallOption) (*bigquerypb.Job, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).InsertJob[0:len((*c.CallOptions).InsertJob):len((*c.CallOptions).InsertJob)], opts...)
	var resp *bigquerypb.Job
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.jobClient.InsertJob, req, settings.GRPC, c.logger, "InsertJob")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *jobGRPCClient) DeleteJob(ctx context.Context, req *bigquerypb.DeleteJobRequest, opts ...gax.CallOption) error {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...)
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		_, err = executeRPC(ctx, c.jobClient.DeleteJob, req, settings.GRPC, c.logger, "DeleteJob")
		return err
	}, opts...)
	return err
}

func (c *jobGRPCClient) ListJobs(ctx context.Context, req *bigquerypb.ListJobsRequest, opts ...gax.CallOption) *ListFormatJobIterator {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...)
	it := &ListFormatJobIterator{}
	req = proto.Clone(req).(*bigquerypb.ListJobsRequest)
	it.InternalFetch = func(pageSize int, pageToken string) ([]*bigquerypb.ListFormatJob, string, error) {
		resp := &bigquerypb.JobList{}
		if pageToken != "" {
			req.PageToken = pageToken
		}
		if pageSize > math.MaxInt32 {
			req.MaxResults = &wrapperspb.Int32Value{Value: math.MaxInt32}
		} else if pageSize != 0 {
			req.MaxResults = &wrapperspb.Int32Value{Value: int32(pageSize)}
		}
		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
			var err error
			resp, err = executeRPC(ctx, c.jobClient.ListJobs, req, settings.GRPC, c.logger, "ListJobs")
			return err
		}, opts...)
		if err != nil {
			return nil, "", err
		}

		it.Response = resp
		return resp.GetJobs(), resp.GetNextPageToken(), nil
	}
	fetch := func(pageSize int, pageToken string) (string, error) {
		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
		if err != nil {
			return "", err
		}
		it.items = append(it.items, items...)
		return nextPageToken, nil
	}

	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
	if psVal := req.GetMaxResults(); psVal != nil {
		it.pageInfo.MaxSize = int(psVal.GetValue())
	}
	it.pageInfo.Token = req.GetPageToken()

	return it
}

func (c *jobGRPCClient) GetQueryResults(ctx context.Context, req *bigquerypb.GetQueryResultsRequest, opts ...gax.CallOption) (*bigquerypb.GetQueryResultsResponse, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).GetQueryResults[0:len((*c.CallOptions).GetQueryResults):len((*c.CallOptions).GetQueryResults)], opts...)
	var resp *bigquerypb.GetQueryResultsResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.jobClient.GetQueryResults, req, settings.GRPC, c.logger, "GetQueryResults")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *jobGRPCClient) Query(ctx context.Context, req *bigquerypb.PostQueryRequest, opts ...gax.CallOption) (*bigquerypb.QueryResponse, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	opts = append((*c.CallOptions).Query[0:len((*c.CallOptions).Query):len((*c.CallOptions).Query)], opts...)
	var resp *bigquerypb.QueryResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.jobClient.Query, req, settings.GRPC, c.logger, "Query")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// CancelJob requests that a job be cancelled. This call will return immediately, and
// the client will need to poll for the job status to see if the cancel
// completed successfully. Cancelled jobs may still incur costs.
func (c *jobRESTClient) CancelJob(ctx context.Context, req *bigquerypb.CancelJobRequest, opts ...gax.CallOption) (*bigquerypb.JobCancelResponse, error) {
	baseUrl, err := url.Parse(c.endpoint)
	if err != nil {
		return nil, err
	}
	baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/jobs/%v/cancel", req.GetProjectId(), req.GetJobId())

	params := url.Values{}
	if req.GetLocation() != "" {
		params.Add("location", fmt.Sprintf("%v", req.GetLocation()))
	}

	baseUrl.RawQuery = params.Encode()

	// Build HTTP headers from client and context metadata.
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	hds = append(hds, "Content-Type", "application/json")
	headers := gax.BuildHeaders(ctx, hds...)
	opts = append((*c.CallOptions).CancelJob[0:len((*c.CallOptions).CancelJob):len((*c.CallOptions).CancelJob)], opts...)
	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
	resp := &bigquerypb.JobCancelResponse{}
	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		if settings.Path != "" {
			baseUrl.Path = settings.Path
		}
		httpReq, err := http.NewRequest("POST", baseUrl.String(), nil)
		if err != nil {
			return err
		}
		httpReq = httpReq.WithContext(ctx)
		httpReq.Header = headers

		buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "CancelJob")
		if err != nil {
			return err
		}

		if err := unm.Unmarshal(buf, resp); err != nil {
			return err
		}

		return nil
	}, opts...)
	if e != nil {
		return nil, e
	}
	return resp, nil
}

// GetJob returns information about a specific job. Job information is available for
// a six month period after creation. Requires that you’re the person who ran
// the job, or have the Is Owner project role.
func (c *jobRESTClient) GetJob(ctx context.Context, req *bigquerypb.GetJobRequest, opts ...gax.CallOption) (*bigquerypb.Job, error) {
	baseUrl, err := url.Parse(c.endpoint)
	if err != nil {
		return nil, err
	}
	baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/jobs/%v", req.GetProjectId(), req.GetJobId())

	params := url.Values{}
	if req.GetLocation() != "" {
		params.Add("location", fmt.Sprintf("%v", req.GetLocation()))
	}

	baseUrl.RawQuery = params.Encode()

	// Build HTTP headers from client and context metadata.
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	hds = append(hds, "Content-Type", "application/json")
	headers := gax.BuildHeaders(ctx, hds...)
	opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...)
	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
	resp := &bigquerypb.Job{}
	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		if settings.Path != "" {
			baseUrl.Path = settings.Path
		}
		httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
		if err != nil {
			return err
		}
		httpReq = httpReq.WithContext(ctx)
		httpReq.Header = headers

		buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "GetJob")
		if err != nil {
			return err
		}

		if err := unm.Unmarshal(buf, resp); err != nil {
			return err
		}

		return nil
	}, opts...)
	if e != nil {
		return nil, e
	}
	return resp, nil
}

// InsertJob starts a new asynchronous job.
//
// This API has two different kinds of endpoint URIs, as this method supports
// a variety of use cases.
//
//	The Metadata URI is used for most interactions, as it accepts the job
//	configuration directly.
//
//	The Upload URI is ONLY for the case when you’re sending both a load job
//	configuration and a data stream together.  In this case, the Upload URI
//	accepts the job configuration and the data as two distinct multipart MIME
//	parts.
func (c *jobRESTClient) InsertJob(ctx context.Context, req *bigquerypb.InsertJobRequest, opts ...gax.CallOption) (*bigquerypb.Job, error) {
	m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
	body := req.GetJob()
	jsonReq, err := m.Marshal(body)
	if err != nil {
		return nil, err
	}

	baseUrl, err := url.Parse(c.endpoint)
	if err != nil {
		return nil, err
	}
	baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/jobs", req.GetProjectId())

	// Build HTTP headers from client and context metadata.
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))}

	hds = append(c.xGoogHeaders, hds...)
	hds = append(hds, "Content-Type", "application/json")
	headers := gax.BuildHeaders(ctx, hds...)
	opts = append((*c.CallOptions).InsertJob[0:len((*c.CallOptions).InsertJob):len((*c.CallOptions).InsertJob)], opts...)
	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
	resp := &bigquerypb.Job{}
	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		if settings.Path != "" {
			baseUrl.Path = settings.Path
		}
		httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
		if err != nil {
			return err
		}
		httpReq = httpReq.WithContext(ctx)
		httpReq.Header = headers

		buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, jsonReq, "InsertJob")
		if err != nil {
			return err
		}

		if err := unm.Unmarshal(buf, resp); err != nil {
			return err
		}

		return nil
	}, opts...)
	if e != nil {
		return nil, e
	}
	return resp, nil
}

// DeleteJob requests the deletion of the metadata of a job. This call returns when the
// job’s metadata is deleted.
func (c *jobRESTClient) DeleteJob(ctx context.Context, req *bigquerypb.DeleteJobRequest, opts ...gax.CallOption) error {
	baseUrl, err := url.Parse(c.endpoint)
	if err != nil {
		return err
	}
	baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/jobs/%v/delete", req.GetProjectId(), req.GetJobId())

	params := url.Values{}
	if req.GetLocation() != "" {
		params.Add("location", fmt.Sprintf("%v", req.GetLocation()))
	}

	baseUrl.RawQuery = params.Encode()

	// Build HTTP headers from client and context metadata.
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	hds = append(hds, "Content-Type", "application/json")
	headers := gax.BuildHeaders(ctx, hds...)
	return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		if settings.Path != "" {
			baseUrl.Path = settings.Path
		}
		httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil)
		if err != nil {
			return err
		}
		httpReq = httpReq.WithContext(ctx)
		httpReq.Header = headers

		_, err = executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "DeleteJob")
		return err
	}, opts...)
}

// ListJobs lists all jobs that you started in the specified project. Job information
// is available for a six month period after creation. The job list is sorted
// in reverse chronological order, by job creation time. Requires the Can View
// project role, or the Is Owner project role if you set the allUsers
// property.
func (c *jobRESTClient) ListJobs(ctx context.Context, req *bigquerypb.ListJobsRequest, opts ...gax.CallOption) *ListFormatJobIterator {
	it := &ListFormatJobIterator{}
	req = proto.Clone(req).(*bigquerypb.ListJobsRequest)
	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
	it.InternalFetch = func(pageSize int, pageToken string) ([]*bigquerypb.ListFormatJob, string, error) {
		resp := &bigquerypb.JobList{}
		if pageToken != "" {
			req.PageToken = pageToken
		}
		if pageSize > math.MaxInt32 {
			req.MaxResults = &wrapperspb.Int32Value{Value: math.MaxInt32}
		} else if pageSize != 0 {
			req.MaxResults = &wrapperspb.Int32Value{Value: int32(pageSize)}
		}
		baseUrl, err := url.Parse(c.endpoint)
		if err != nil {
			return nil, "", err
		}
		baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/jobs", req.GetProjectId())

		params := url.Values{}
		if req.GetAllUsers() {
			params.Add("allUsers", fmt.Sprintf("%v", req.GetAllUsers()))
		}
		if req.GetMaxCreationTime() != nil {
			field, err := protojson.Marshal(req.GetMaxCreationTime())
			if err != nil {
				return nil, "", err
			}
			params.Add("maxCreationTime", string(field))
		}
		if req.GetMaxResults() != nil {
			field, err := protojson.Marshal(req.GetMaxResults())
			if err != nil {
				return nil, "", err
			}
			params.Add("maxResults", string(field))
		}
		if req.GetMinCreationTime() != 0 {
			params.Add("minCreationTime", fmt.Sprintf("%v", req.GetMinCreationTime()))
		}
		if req.GetPageToken() != "" {
			params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
		}
		if req.GetParentJobId() != "" {
			params.Add("parentJobId", fmt.Sprintf("%v", req.GetParentJobId()))
		}
		if req.GetProjection() != 0 {
			params.Add("projection", fmt.Sprintf("%v", req.GetProjection()))
		}
		if items := req.GetStateFilter(); len(items) > 0 {
			for _, item := range items {
				params.Add("stateFilter", fmt.Sprintf("%v", item))
			}
		}

		baseUrl.RawQuery = params.Encode()

		// Build HTTP headers from client and context metadata.
		hds := append(c.xGoogHeaders, "Content-Type", "application/json")
		headers := gax.BuildHeaders(ctx, hds...)
		e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
			if settings.Path != "" {
				baseUrl.Path = settings.Path
			}
			httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
			if err != nil {
				return err
			}
			httpReq.Header = headers

			buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "ListJobs")
			if err != nil {
				return err
			}
			if err := unm.Unmarshal(buf, resp); err != nil {
				return err
			}

			return nil
		}, opts...)
		if e != nil {
			return nil, "", e
		}
		it.Response = resp
		return resp.GetJobs(), resp.GetNextPageToken(), nil
	}

	fetch := func(pageSize int, pageToken string) (string, error) {
		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
		if err != nil {
			return "", err
		}
		it.items = append(it.items, items...)
		return nextPageToken, nil
	}

	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
	if psVal := req.GetMaxResults(); psVal != nil {
		it.pageInfo.MaxSize = int(psVal.GetValue())
	}
	it.pageInfo.Token = req.GetPageToken()

	return it
}

// GetQueryResults rPC to get the results of a query job.
func (c *jobRESTClient) GetQueryResults(ctx context.Context, req *bigquerypb.GetQueryResultsRequest, opts ...gax.CallOption) (*bigquerypb.GetQueryResultsResponse, error) {
	baseUrl, err := url.Parse(c.endpoint)
	if err != nil {
		return nil, err
	}
	baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/queries/%v", req.GetProjectId(), req.GetJobId())

	params := url.Values{}
	if req.GetFormatOptions().GetTimestampOutputFormat() != 0 {
		params.Add("formatOptions.timestampOutputFormat", fmt.Sprintf("%v", req.GetFormatOptions().GetTimestampOutputFormat()))
	}
	if req.GetFormatOptions().GetUseInt64Timestamp() {
		params.Add("formatOptions.useInt64Timestamp", fmt.Sprintf("%v", req.GetFormatOptions().GetUseInt64Timestamp()))
	}
	if req.GetLocation() != "" {
		params.Add("location", fmt.Sprintf("%v", req.GetLocation()))
	}
	if req.GetMaxResults() != nil {
		field, err := protojson.Marshal(req.GetMaxResults())
		if err != nil {
			return nil, err
		}
		params.Add("maxResults", string(field))
	}
	if req.GetPageToken() != "" {
		params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
	}
	if req.GetStartIndex() != nil {
		field, err := protojson.Marshal(req.GetStartIndex())
		if err != nil {
			return nil, err
		}
		params.Add("startIndex", string(field))
	}
	if req.GetTimeoutMs() != nil {
		field, err := protojson.Marshal(req.GetTimeoutMs())
		if err != nil {
			return nil, err
		}
		params.Add("timeoutMs", string(field))
	}

	baseUrl.RawQuery = params.Encode()

	// Build HTTP headers from client and context metadata.
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "job_id", url.QueryEscape(req.GetJobId()))}

	hds = append(c.xGoogHeaders, hds...)
	hds = append(hds, "Content-Type", "application/json")
	headers := gax.BuildHeaders(ctx, hds...)
	opts = append((*c.CallOptions).GetQueryResults[0:len((*c.CallOptions).GetQueryResults):len((*c.CallOptions).GetQueryResults)], opts...)
	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
	resp := &bigquerypb.GetQueryResultsResponse{}
	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		if settings.Path != "" {
			baseUrl.Path = settings.Path
		}
		httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
		if err != nil {
			return err
		}
		httpReq = httpReq.WithContext(ctx)
		httpReq.Header = headers

		buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "GetQueryResults")
		if err != nil {
			return err
		}

		if err := unm.Unmarshal(buf, resp); err != nil {
			return err
		}

		return nil
	}, opts...)
	if e != nil {
		return nil, e
	}
	return resp, nil
}

// Query runs a BigQuery SQL query synchronously and returns query results if the
// query completes within a specified timeout.
func (c *jobRESTClient) Query(ctx context.Context, req *bigquerypb.PostQueryRequest, opts ...gax.CallOption) (*bigquerypb.QueryResponse, error) {
	m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
	body := req.GetQueryRequest()
	jsonReq, err := m.Marshal(body)
	if err != nil {
		return nil, err
	}

	baseUrl, err := url.Parse(c.endpoint)
	if err != nil {
		return nil, err
	}
	baseUrl.Path += fmt.Sprintf("/bigquery/v2/projects/%v/queries", req.GetProjectId())

	// Build HTTP headers from client and context metadata.
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))}

	hds = append(c.xGoogHeaders, hds...)
	hds = append(hds, "Content-Type", "application/json")
	headers := gax.BuildHeaders(ctx, hds...)
	opts = append((*c.CallOptions).Query[0:len((*c.CallOptions).Query):len((*c.CallOptions).Query)], opts...)
	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
	resp := &bigquerypb.QueryResponse{}
	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		if settings.Path != "" {
			baseUrl.Path = settings.Path
		}
		httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
		if err != nil {
			return err
		}
		httpReq = httpReq.WithContext(ctx)
		httpReq.Header = headers

		buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, jsonReq, "Query")
		if err != nil {
			return err
		}

		if err := unm.Unmarshal(buf, resp); err != nil {
			return err
		}

		return nil
	}, opts...)
	if e != nil {
		return nil, e
	}
	return resp, nil
}
