package basic

import (
	"context"
	"fmt"

	"github.com/mitchellh/mapstructure"

	"github.com/tidbcloud/eks-provider/controllers/workflow/action"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/consts"
)

// abortAction aborts the workflow if the input Abort is true
type abortAction struct{}

type abortInputs struct {
	Abort   bool   `mapstructure:"abort" json:"abort" validate:"required"`
	Message string `mapstructure:"message" json:"message" validate:"omitempty"`
}

var (
	_ action.Action = &abortAction{}
)

func init() {
	action.RegisterWorkflowAction(&abortAction{})
}

func (d *abortAction) Name() cloudv1.WorkflowActionName {
	return consts.WorkflowActionAbort
}

func (d *abortAction) PreCheck(ctx context.Context, wf *cloudv1.Workflow, step cloudv1.WorkflowStep) error {
	inputs := &abortInputs{}
	if err := mapstructure.Decode(step.Inputs.Object, &inputs); err != nil {
		return fmt.Errorf("decode inputs: %w", err)
	}
	return nil
}

func (d *abortAction) Handle(ctx context.Context, wf *cloudv1.Workflow, step cloudv1.WorkflowStep) error {
	inputs := &abortInputs{}
	if err := mapstructure.Decode(step.Inputs.Object, &inputs); err != nil {
		return fmt.Errorf("decode inputs: %w", err)
	}

	if inputs.Abort {
		return cloudv1.NewWFAbortedError(fmt.Errorf("aborted with: %s", inputs.Message))
	}

	return nil
}
