package cmd

import (
	"encoding/json"
	"github.com/spf13/cobra"
	"github.com/tidbcloud/dataflow-service/app/container"
	"github.com/tidbcloud/dataflow-service/app/models/domain"
	bootstarpSerer "github.com/tidbcloud/dataflow-service/internal/cmd/bootstrap/server"
	"github.com/tidbcloud/dataflow-service/pkg/log"
	"go.uber.org/zap"
)

func registerTiDBGCJobFunc(cmd *cobra.Command) {
	{
		var reqString string
		suBcmd := &cobra.Command{
			Use:   "enable-tidb-gc",
			Short: "enable-tidb-gc",
			RunE: func(cmd *cobra.Command, args []string) error {
				if _, err := bootstarpSerer.NewServer(cmd.Context(), bootstarpSerer.ServerOption{
					EnableEventBusConsumer: false,
				}); err != nil {
					return err
				}
				ctx := log.WithTraceID(cmd.Context())
				app := container.Global()
				req := &domain.EnableTiDBClusterGCSwitchReq{}
				err := json.Unmarshal([]byte(reqString), req)
				if err != nil {
					log.GetLogger(ctx).Error("unmarshal reqString", zap.Error(err))
					return err
				}
				resp, err := app.TiDBClusterGCSwitchModel.Enable(ctx, req)
				if err != nil {
					log.GetLogger(ctx).Error("enable cluster gc", zap.Error(err))
					return err
				}
				log.GetLogger(ctx).Info("enable tidb cluster gc success", zap.Any("resp", resp))
				return nil
			},
		}
		suBcmd.Flags().StringVarP(&reqString, "request", "", "", "")
		cmd.AddCommand(suBcmd)
	}

	{
		var reqString string
		suBcmd := &cobra.Command{
			Use:   "disable-tidb-gc",
			Short: "disable-tidb-gc",
			RunE: func(cmd *cobra.Command, args []string) error {
				if _, err := bootstarpSerer.NewServer(cmd.Context(), bootstarpSerer.ServerOption{
					EnableEventBusConsumer: false,
				}); err != nil {
					return err
				}
				ctx := log.WithTraceID(cmd.Context())
				app := container.Global()
				req := &domain.DisableTiDBClusterGCSwitchReq{}
				err := json.Unmarshal([]byte(reqString), req)
				if err != nil {
					log.GetLogger(ctx).Error("unmarshal req", zap.Error(err))
					return err
				}
				resp, err := app.TiDBClusterGCSwitchModel.Disable(ctx, req)
				if err != nil {
					log.GetLogger(ctx).Error("disable tidb cluster gc", zap.Error(err))
					return err
				}
				log.GetLogger(ctx).Info("disable tidb cluster gc success", zap.Any("resp", resp))
				return nil
			},
		}
		suBcmd.Flags().StringVarP(&reqString, "request", "", "", "")
		cmd.AddCommand(suBcmd)
	}

}

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

	registerTiDBGCJobFunc(cmd)
	jobCmd.AddCommand(cmd)
}
