package disable

import (
	"context"

	crrfRepo "github.com/tidbcloud/dataflow-service/app/repo/crrf"
	"github.com/tidbcloud/dataflow-service/app/workflow"
	"github.com/tidbcloud/dataflow-service/app/workflow/action"
	"go.uber.org/zap"
)

type markDisabledParams struct {
	ClusterID uint64 `json:"cluster_id"`
}

type markDisabledAction struct {
	crrfSettingRepo crrfRepo.CRRFSettingRepo
}

// NewMarkDisabledAction returns a Wrapper that transitions CRRFSetting status from disabling to disabled
// and clears all CRRF-specific fields. This is the final action in the disable_crrf DAG.
func NewMarkDisabledAction(crrfSettingRepo crrfRepo.CRRFSettingRepo) *action.Wrapper {
	return action.MustNewActionWrapper(
		workflow.ActionCRRFMarkDisabled,
		&markDisabledAction{crrfSettingRepo: crrfSettingRepo},
	)
}

func (a *markDisabledAction) Params() interface{} {
	return &markDisabledParams{}
}

func (a *markDisabledAction) Run(ctx context.Context, logger *zap.Logger, params interface{}) error {
	p := params.(*markDisabledParams)

	setting, bizErr := a.crrfSettingRepo.GetByClusterID(ctx, p.ClusterID)
	if bizErr != nil {
		return bizErr
	}
	changed, err := setting.Disable(ctx)
	if err != nil {
		return err
	}
	if !changed {
		return nil
	}

	if saveErr := a.crrfSettingRepo.Save(ctx, setting); saveErr != nil {
		return saveErr
	}

	logger.Info("crrf setting marked as disabled", zap.Uint64("clusterID", p.ClusterID))
	return nil
}
