package dedicated

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

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

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

var (
	dedicatedGlobalCoreSvcOnce  sync.Once
	dedicatedGlobalTiDBGroupCli globaldedicatedv1.TidbNodeGroupServiceClient
	dedicatedGlobalClusterOnce  sync.Once
	dedicatedGlobalClusterCli   globaldedicatedv1.ClusterServiceClient
)

func getDedicatedGlobalCoreClient() globaldedicatedv1.TidbNodeGroupServiceClient {
	dedicatedGlobalCoreSvcOnce.Do(func() {
		timeout := time.Duration(config.Config().Grpc.Timeout) * time.Second
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		defer cancel()

		addr := config.Config().Grpc.DedicatedGlobalAddr
		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 dedicated core svc: %s", err))
		}
		dedicatedGlobalTiDBGroupCli = globaldedicatedv1.NewTidbNodeGroupServiceClient(conn)
	})

	return dedicatedGlobalTiDBGroupCli
}

func UpdateTidbNodeGroup(
	ctx context.Context,
	req *globaldedicatedv1.UpdateTidbNodeGroupRequest,
) (*globaldedicatedv1.TidbNodeGroup, error) {
	client := getDedicatedGlobalCoreClient()

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

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

		addr := config.Config().Grpc.DedicatedGlobalAddr
		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 dedicated cluster service: %s", err))
		}
		dedicatedGlobalClusterCli = globaldedicatedv1.NewClusterServiceClient(conn)
	})

	return dedicatedGlobalClusterCli
}

func ChangeClusterPassword(
	ctx context.Context,
	req *globaldedicatedv1.ChangeClusterPasswdRequest,
) (*globaldedicatedv1.ChangeClusterPasswdResponse, error) {
	return getDedicatedGlobalClusterClient().ChangeClusterPasswd(ctx, req)
}
