package tenantaction

import (
	"context"

	opent "github.com/tidbcloud/devops/entity/operation"
	"github.com/tidbcloud/devops/pkg/service/operation/actions"
)

var (
	ActionDeleteUser opent.ActionMetadata = opent.ActionMetadata{
		Name: "DeleteUser",
		Type: opent.ActionTypeAuto,
	}
)

type deleteUser struct {
	actions.BaseAction
	comps *actions.Components
}

func NewDeleteUser(comps *actions.Components) actions.AutoAction {
	return &deleteUser{comps: comps}
}

func (a *deleteUser) Metadata() opent.ActionMetadata {
	return ActionDeleteUser
}

func (a *deleteUser) PreCheck(ctx context.Context, instance *opent.Instance) error {
	return nil
}

func (a *deleteUser) Start(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	uid, err := a.getParam(instance)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}
	err = a.comps.TenantAPI.DeleteUser(ctx, uid, instance.Applicant)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}

	return actions.SucceededActionResult(nil), nil
}

func (a *deleteUser) Result(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	return actions.SucceededActionResult(nil), nil
}

func (a *deleteUser) getParam(instance *opent.Instance) (string, error) {
	// uid is required
	uid, err := actions.GetUserIDStr(instance)
	if err != nil {
		return "", err
	}

	return uid, nil
}
