package tenantaction

import (
	"context"

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

var (
	ActionDeleteProject opent.ActionMetadata = opent.ActionMetadata{
		Name: "DeleteProject",
		Type: opent.ActionTypeAuto,
	}
)

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

func NewDeleteProject(comps *actions.Components) actions.AutoAction {
	return &deleteProject{comps: comps}
}

func (a *deleteProject) Metadata() opent.ActionMetadata {
	return ActionDeleteProject
}

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

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

	return actions.SucceededActionResult(nil), nil
}

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

func (a *deleteProject) getParam(instance *opent.Instance) (string, string, error) {
	oid, err := actions.GetTenantIDStr(instance)
	if err != nil {
		return "", "", err
	}
	pid, err := actions.GetProjectIDStr(instance)
	if err != nil {
		return "", "", err
	}

	return oid, pid, nil
}
