package tenantaction

import (
	"context"
	"fmt"
	"strconv"

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

var (
	ActionAddUserToTenant opent.ActionMetadata = opent.ActionMetadata{
		Name: "AddUserToTenant",
		Type: opent.ActionTypeAuto,
	}
)

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

func NewAddUserToTenant(comps *actions.Components) actions.AutoAction {
	return &addUserToTenant{comps: comps}
}

func (a *addUserToTenant) Metadata() opent.ActionMetadata {
	return ActionAddUserToTenant
}

func (a *addUserToTenant) PreCheck(ctx context.Context, instance *opent.Instance) error {
	oid, _, _, err := a.getParam(instance)
	if err != nil {
		return err
	}
	id, err := strconv.ParseUint(oid, 10, 64)
	if err != nil {
		return err
	}
	_, err = a.comps.TenantAPI.GetTenant(ctx, id)
	if err != nil {
		return err
	}
	return nil
}

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

	return actions.SucceededActionResult(nil), nil
}

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

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

	uid, err := actions.GetUserIDStr(instance)
	if err != nil {
		return "", "", "", err
	}

	role, _ := instance.GetParam(opent.ParamUserRole)
	if role == "" {
		return "", "", "", fmt.Errorf("user_role is required")
	}

	return oid, uid, role, nil
}
