package cmd

import (
	"encoding/json"

	"github.com/spf13/cobra"
	"github.com/tidbcloud/core-svc/idl/pbgen/proto/core"
	"github.com/tidbcloud/dataflow-service/app/container"
	bootstarpSerer "github.com/tidbcloud/dataflow-service/internal/cmd/bootstrap/server"
	"github.com/tidbcloud/dataflow-service/pkg/log"
	"go.uber.org/zap"
)

func registerCoreSvcJobFunc(cmd *cobra.Command) {
	{
		var clusterID uint64
		suBcmd := &cobra.Command{
			Use:   "get_access_points",
			Short: "get access points of a cluster",
			RunE: func(cmd *cobra.Command, args []string) error {
				return callFuncAfterServerInitialized(cmd, func() error {
					ctx := log.WithTraceID(cmd.Context())
					logger := log.GetLogger(ctx)
					accessPoints, err := container.Global().CoreGrpcClient.GetClusterAccessPoints(ctx, clusterID)
					if err != nil {
						logger.Error("GetClusterAccessPoints error", zap.Error(err))
						return err
					}
					bin, _ := json.Marshal(accessPoints)
					logger.Info("The query result", zap.Any("access points", string(bin)))
					return nil
				})
			},
		}
		suBcmd.Flags().Uint64VarP(&clusterID, "clusterID", "", 0, "")
		cmd.AddCommand(suBcmd)
	}

	{
		var clusterID uint64
		var anyCluster bool
		suBcmd := &cobra.Command{
			Use:   "query_cluster",
			Short: "query a cluster detail by id",
			RunE: func(cmd *cobra.Command, args []string) error {
				return callFuncAfterServerInitialized(cmd, func() error {
					ctx := log.WithTraceID(cmd.Context())
					logger := log.GetLogger(ctx)
					var (
						cluster *core.Cluster
						err     error
					)
					if anyCluster {
						cluster, err = container.Global().CoreGrpcClient.GetAnyClusterByID(ctx, clusterID)
					} else {
						cluster, err = container.Global().CoreGrpcClient.GetAvailableClusterByID(ctx, clusterID)
					}
					if err != nil {
						logger.Error("GetAvailableClusterByID error", zap.Error(err))
						return err
					}
					bin, _ := json.Marshal(cluster)
					logger.Info("The query result", zap.Any("cluster", string(bin)))
					return nil
				})
			},
		}
		suBcmd.Flags().Uint64VarP(&clusterID, "cluster-id", "", 0, "the tidb cloud cluster id")
		suBcmd.Flags().BoolVarP(&anyCluster, "any", "", false, "list any available cluster")
		cmd.AddCommand(suBcmd)
	}
}

func init() {
	coreSvcCmd := &cobra.Command{Use: "coresvc", Short: "coresvc cmd"}
	coreSvcCmd.PreRunE = func(cmd *cobra.Command, args []string) error {
		return nil
	}

	registerCoreSvcJobFunc(coreSvcCmd)
	jobCmd.AddCommand(coreSvcCmd)
}

func callFuncAfterServerInitialized(cmd *cobra.Command, f func() error) error {
	if _, err := bootstarpSerer.NewServer(cmd.Context(), bootstarpSerer.ServerOption{
		EnableEventBusConsumer: false,
	}); err != nil {
		return err
	}
	return f()
}
