package mgmt

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	"github.com/sercand/kuberesolver/v5"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
	"google.golang.org/grpc"

	tidbmgmtservicev1 "github.com/tidbcloud/tidb-management-service/api/spec/tidb_mgmt_service/v1"
	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/internal/config"
	grpcutil "github.com/tidbcloud/tidb-management-service/utilities/grpc"
)

var (
	mgmtInternalSvcOnce sync.Once
	mgmtInternalSvcCli  tidbmgmtservicev1.ClusterServiceClient
)

func getMgmtInternalSvcClient() tidbmgmtservicev1.ClusterServiceClient {
	mgmtInternalSvcOnce.Do(func() {
		timeout := time.Duration(config.Config().Grpc.Timeout) * time.Second
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		defer cancel()

		addr := config.Config().Grpc.MgmtSvcAddr
		interceptors := []grpc.UnaryClientInterceptor{
			grpcutil.TimeoutInterceptor(timeout),
			grpcutil.ClientPayloadLogInterceptor,
		}
		opts := []tigrpc.Option{
			tigrpc.WithDefault(),
			tigrpc.WithUnaryInterceptors(interceptors...),
		}
		if strings.HasPrefix(addr, "kubernetes://") {
			kuberesolver.RegisterInCluster()
			opts = append(opts, tigrpc.WithLoadBalance())
		}

		conn, err := tigrpc.NewClientContext(ctx, addr, opts...)
		if err != nil {
			panic(fmt.Sprintf("dial mgmt-serverless-svc: %s", err))
		}
		mgmtInternalSvcCli = tidbmgmtservicev1.NewClusterServiceClient(conn)
	})

	return mgmtInternalSvcCli
}

func InternalListClusters(
	ctx context.Context,
	req *tidbmgmtservicev1.ListClustersRequest,
) (*tidbmgmtservicev1.ListClustersResponse, error) {
	client := getMgmtInternalSvcClient()

	resp, err := client.ListClusters(ctx, req)
	// need to set default page size
	req.PageSize = defaultListClusterPageSize
	if err != nil {
		return resp, err
	}
	return resp, nil
}

func CreateClusterWithClusterConfiguration(
	ctx context.Context,
	req *tidbmgmtservicev1.CreateClusterWithClusterConfigurationRequest,
) (*tidbmgmtservicev1.Cluster, error) {
	client := getMgmtInternalSvcClient()

	resp, err := client.CreateClusterWithClusterConfiguration(ctx, req)
	if err != nil {
		return resp, err
	}
	return resp, nil
}

func ShowDedicatedComponentNodeInfo(
	ctx context.Context,
	req *tidbmgmtservicev1.ShowComponentNodeInfoRequest,
) (*tidbmgmtservicev1.ShowComponentNodeInfoResponse, error) {
	client := getMgmtInternalSvcClient()

	resp, err := client.ShowComponentNodeInfo(ctx, req)
	if err != nil {
		return resp, err
	}
	return resp, nil
}

func CountBillableClusters(
	ctx context.Context,
	req *tidbmgmtservicev1.CountBillableClustersRequest,
) (*tidbmgmtservicev1.CountBillableClustersResponse, error) {
	client := getMgmtInternalSvcClient()

	resp, err := client.CountBillableClusters(ctx, req)
	if err != nil {
		return resp, err
	}
	return resp, nil
}
