// Copyright 2026 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 storage

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

	storagepb "cloud.google.com/go/bigquery/storage/apiv1alpha/storagepb"
	gax "github.com/googleapis/gax-go/v2"
	"github.com/googleapis/gax-go/v2/callctx"
	"google.golang.org/api/option"
	"google.golang.org/api/option/internaloption"
	gtransport "google.golang.org/api/transport/grpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

var newMetastorePartitionClientHook clientHook

// MetastorePartitionCallOptions contains the retry settings for each method of MetastorePartitionClient.
type MetastorePartitionCallOptions struct {
	BatchCreateMetastorePartitions []gax.CallOption
	BatchDeleteMetastorePartitions []gax.CallOption
	BatchUpdateMetastorePartitions []gax.CallOption
	ListMetastorePartitions        []gax.CallOption
	StreamMetastorePartitions      []gax.CallOption
}

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

func defaultMetastorePartitionCallOptions() *MetastorePartitionCallOptions {
	return &MetastorePartitionCallOptions{
		BatchCreateMetastorePartitions: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.Unavailable,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		BatchDeleteMetastorePartitions: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.Unavailable,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		BatchUpdateMetastorePartitions: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.Unavailable,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		ListMetastorePartitions: []gax.CallOption{
			gax.WithTimeout(240000 * time.Millisecond),
			gax.WithRetry(func() gax.Retryer {
				return gax.OnCodes([]codes.Code{
					codes.Unavailable,
				}, gax.Backoff{
					Initial:    100 * time.Millisecond,
					Max:        60000 * time.Millisecond,
					Multiplier: 1.30,
				})
			}),
		},
		StreamMetastorePartitions: []gax.CallOption{},
	}
}

// internalMetastorePartitionClient is an interface that defines the methods available from BigQuery Storage API.
type internalMetastorePartitionClient interface {
	Close() error
	setGoogleClientInfo(...string)
	Connection() *grpc.ClientConn
	BatchCreateMetastorePartitions(context.Context, *storagepb.BatchCreateMetastorePartitionsRequest, ...gax.CallOption) (*storagepb.BatchCreateMetastorePartitionsResponse, error)
	BatchDeleteMetastorePartitions(context.Context, *storagepb.BatchDeleteMetastorePartitionsRequest, ...gax.CallOption) error
	BatchUpdateMetastorePartitions(context.Context, *storagepb.BatchUpdateMetastorePartitionsRequest, ...gax.CallOption) (*storagepb.BatchUpdateMetastorePartitionsResponse, error)
	ListMetastorePartitions(context.Context, *storagepb.ListMetastorePartitionsRequest, ...gax.CallOption) (*storagepb.ListMetastorePartitionsResponse, error)
	StreamMetastorePartitions(context.Context, ...gax.CallOption) (storagepb.MetastorePartitionService_StreamMetastorePartitionsClient, error)
}

// MetastorePartitionClient is a client for interacting with BigQuery Storage API.
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
//
// BigQuery Metastore Partition Service API.
// This service is used for managing metastore partitions in BigQuery
// metastore. The service supports only batch operations for write.
type MetastorePartitionClient struct {
	// The internal transport-dependent client.
	internalClient internalMetastorePartitionClient

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

// Wrapper methods routed to the internal client.

// Close closes the connection to the API service. **Always** call Close() when
// the client is no longer required.
func (c *MetastorePartitionClient) 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 *MetastorePartitionClient) 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 *MetastorePartitionClient) Connection() *grpc.ClientConn {
	return c.internalClient.Connection()
}

// BatchCreateMetastorePartitions adds metastore partitions to a table.
func (c *MetastorePartitionClient) BatchCreateMetastorePartitions(ctx context.Context, req *storagepb.BatchCreateMetastorePartitionsRequest, opts ...gax.CallOption) (*storagepb.BatchCreateMetastorePartitionsResponse, error) {
	return c.internalClient.BatchCreateMetastorePartitions(ctx, req, opts...)
}

// BatchDeleteMetastorePartitions deletes metastore partitions from a table.
func (c *MetastorePartitionClient) BatchDeleteMetastorePartitions(ctx context.Context, req *storagepb.BatchDeleteMetastorePartitionsRequest, opts ...gax.CallOption) error {
	return c.internalClient.BatchDeleteMetastorePartitions(ctx, req, opts...)
}

// BatchUpdateMetastorePartitions updates metastore partitions in a table.
func (c *MetastorePartitionClient) BatchUpdateMetastorePartitions(ctx context.Context, req *storagepb.BatchUpdateMetastorePartitionsRequest, opts ...gax.CallOption) (*storagepb.BatchUpdateMetastorePartitionsResponse, error) {
	return c.internalClient.BatchUpdateMetastorePartitions(ctx, req, opts...)
}

// ListMetastorePartitions gets metastore partitions from a table.
func (c *MetastorePartitionClient) ListMetastorePartitions(ctx context.Context, req *storagepb.ListMetastorePartitionsRequest, opts ...gax.CallOption) (*storagepb.ListMetastorePartitionsResponse, error) {
	return c.internalClient.ListMetastorePartitions(ctx, req, opts...)
}

// StreamMetastorePartitions this is a bi-di streaming rpc method that allows the client to send
// a stream of partitions and commit all of them atomically at the end.
// If the commit is successful, the server will return a
// response and close the stream. If the commit fails (due to duplicate
// partitions or other reason), the server will close the stream with an
// error. This method is only available via the gRPC API (not REST).
func (c *MetastorePartitionClient) StreamMetastorePartitions(ctx context.Context, opts ...gax.CallOption) (storagepb.MetastorePartitionService_StreamMetastorePartitionsClient, error) {
	return c.internalClient.StreamMetastorePartitions(ctx, opts...)
}

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

	// Points back to the CallOptions field of the containing MetastorePartitionClient
	CallOptions **MetastorePartitionCallOptions

	// The gRPC API client.
	metastorePartitionClient storagepb.MetastorePartitionServiceClient

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

	logger *slog.Logger
}

// NewMetastorePartitionClient creates a new metastore partition service client based on gRPC.
// The returned client must be Closed when it is done being used to clean up its underlying connections.
//
// BigQuery Metastore Partition Service API.
// This service is used for managing metastore partitions in BigQuery
// metastore. The service supports only batch operations for write.
func NewMetastorePartitionClient(ctx context.Context, opts ...option.ClientOption) (*MetastorePartitionClient, error) {
	clientOpts := defaultMetastorePartitionGRPCClientOptions()
	if gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		clientOpts = append(clientOpts, internaloption.WithTelemetryAttributes(map[string]string{
			"gcp.client.service":  "bigquerystorage",
			"gcp.client.version":  getVersionClient(),
			"gcp.client.repo":     "googleapis/google-cloud-go",
			"gcp.client.artifact": "cloud.google.com/go/bigquery/storage/apiv1alpha",
			"gcp.client.language": "go",
			"url.domain":          "bigquerystorage.googleapis.com",
		}))
	}
	if newMetastorePartitionClientHook != nil {
		hookOpts, err := newMetastorePartitionClientHook(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 := MetastorePartitionClient{CallOptions: defaultMetastorePartitionCallOptions()}

	c := &metastorePartitionGRPCClient{
		connPool:                 connPool,
		metastorePartitionClient: storagepb.NewMetastorePartitionServiceClient(connPool),
		CallOptions:              &client.CallOptions,
		logger:                   internaloption.GetLogger(opts),
	}
	c.setGoogleClientInfo()
	if gax.IsFeatureEnabled("METRICS") {
		metrics := gax.NewClientMetrics(
			gax.WithTelemetryLogger(c.logger),
			gax.WithTelemetryAttributes(map[string]string{
				gax.ClientService:  "bigquerystorage",
				gax.ClientVersion:  getVersionClient(),
				gax.ClientArtifact: "cloud.google.com/go/bigquery/storage/apiv1alpha",
				gax.RPCSystem:      "grpc",
				gax.URLDomain:      "bigquerystorage.googleapis.com",
			}),
		)

		client.CallOptions.BatchCreateMetastorePartitions = append(client.CallOptions.BatchCreateMetastorePartitions, gax.WithClientMetrics(metrics))
		client.CallOptions.BatchDeleteMetastorePartitions = append(client.CallOptions.BatchDeleteMetastorePartitions, gax.WithClientMetrics(metrics))
		client.CallOptions.BatchUpdateMetastorePartitions = append(client.CallOptions.BatchUpdateMetastorePartitions, gax.WithClientMetrics(metrics))
		client.CallOptions.ListMetastorePartitions = append(client.CallOptions.ListMetastorePartitions, gax.WithClientMetrics(metrics))
		client.CallOptions.StreamMetastorePartitions = append(client.CallOptions.StreamMetastorePartitions, gax.WithClientMetrics(metrics))
	}

	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 *metastorePartitionGRPCClient) 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 *metastorePartitionGRPCClient) 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. **Always** call Close() when
// the client is no longer required.
func (c *metastorePartitionGRPCClient) Close() error {
	return c.connPool.Close()
}

func (c *metastorePartitionGRPCClient) BatchCreateMetastorePartitions(ctx context.Context, req *storagepb.BatchCreateMetastorePartitionsRequest, opts ...gax.CallOption) (*storagepb.BatchCreateMetastorePartitionsResponse, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	if gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "resource_name", fmt.Sprintf("//bigquerystorage.googleapis.com/%v", req.GetParent()))
	}
	if gax.IsFeatureEnabled("METRICS") || gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "rpc_method", "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService/BatchCreateMetastorePartitions")
	}
	opts = append((*c.CallOptions).BatchCreateMetastorePartitions[0:len((*c.CallOptions).BatchCreateMetastorePartitions):len((*c.CallOptions).BatchCreateMetastorePartitions)], opts...)
	var resp *storagepb.BatchCreateMetastorePartitionsResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.metastorePartitionClient.BatchCreateMetastorePartitions, req, settings.GRPC, c.logger, "BatchCreateMetastorePartitions")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *metastorePartitionGRPCClient) BatchDeleteMetastorePartitions(ctx context.Context, req *storagepb.BatchDeleteMetastorePartitionsRequest, opts ...gax.CallOption) error {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	if gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "resource_name", fmt.Sprintf("//bigquerystorage.googleapis.com/%v", req.GetParent()))
	}
	if gax.IsFeatureEnabled("METRICS") || gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "rpc_method", "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService/BatchDeleteMetastorePartitions")
	}
	opts = append((*c.CallOptions).BatchDeleteMetastorePartitions[0:len((*c.CallOptions).BatchDeleteMetastorePartitions):len((*c.CallOptions).BatchDeleteMetastorePartitions)], opts...)
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		_, err = executeRPC(ctx, c.metastorePartitionClient.BatchDeleteMetastorePartitions, req, settings.GRPC, c.logger, "BatchDeleteMetastorePartitions")
		return err
	}, opts...)
	return err
}

func (c *metastorePartitionGRPCClient) BatchUpdateMetastorePartitions(ctx context.Context, req *storagepb.BatchUpdateMetastorePartitionsRequest, opts ...gax.CallOption) (*storagepb.BatchUpdateMetastorePartitionsResponse, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	if gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "resource_name", fmt.Sprintf("//bigquerystorage.googleapis.com/%v", req.GetParent()))
	}
	if gax.IsFeatureEnabled("METRICS") || gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "rpc_method", "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService/BatchUpdateMetastorePartitions")
	}
	opts = append((*c.CallOptions).BatchUpdateMetastorePartitions[0:len((*c.CallOptions).BatchUpdateMetastorePartitions):len((*c.CallOptions).BatchUpdateMetastorePartitions)], opts...)
	var resp *storagepb.BatchUpdateMetastorePartitionsResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.metastorePartitionClient.BatchUpdateMetastorePartitions, req, settings.GRPC, c.logger, "BatchUpdateMetastorePartitions")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *metastorePartitionGRPCClient) ListMetastorePartitions(ctx context.Context, req *storagepb.ListMetastorePartitionsRequest, opts ...gax.CallOption) (*storagepb.ListMetastorePartitionsResponse, error) {
	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}

	hds = append(c.xGoogHeaders, hds...)
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
	if gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "resource_name", fmt.Sprintf("//bigquerystorage.googleapis.com/%v", req.GetParent()))
	}
	if gax.IsFeatureEnabled("METRICS") || gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "rpc_method", "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService/ListMetastorePartitions")
	}
	opts = append((*c.CallOptions).ListMetastorePartitions[0:len((*c.CallOptions).ListMetastorePartitions):len((*c.CallOptions).ListMetastorePartitions)], opts...)
	var resp *storagepb.ListMetastorePartitionsResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = executeRPC(ctx, c.metastorePartitionClient.ListMetastorePartitions, req, settings.GRPC, c.logger, "ListMetastorePartitions")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *metastorePartitionGRPCClient) StreamMetastorePartitions(ctx context.Context, opts ...gax.CallOption) (storagepb.MetastorePartitionService_StreamMetastorePartitionsClient, error) {
	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, c.xGoogHeaders...)
	if gax.IsFeatureEnabled("METRICS") || gax.IsFeatureEnabled("TRACING") || gax.IsFeatureEnabled("LOGGING") {
		ctx = callctx.WithTelemetryContext(ctx, "rpc_method", "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService/StreamMetastorePartitions")
	}
	var resp storagepb.MetastorePartitionService_StreamMetastorePartitionsClient
	opts = append((*c.CallOptions).StreamMetastorePartitions[0:len((*c.CallOptions).StreamMetastorePartitions):len((*c.CallOptions).StreamMetastorePartitions)], opts...)
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		c.logger.DebugContext(ctx, "api streaming client request", "serviceName", serviceName, "rpcName", "StreamMetastorePartitions")
		resp, err = c.metastorePartitionClient.StreamMetastorePartitions(ctx, settings.GRPC...)
		c.logger.DebugContext(ctx, "api streaming client response", "serviceName", serviceName, "rpcName", "StreamMetastorePartitions")
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
