package tenantaction

import (
	"context"
	"fmt"
	"strconv"

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

var (
	ActionAddUserToProject opent.ActionMetadata = opent.ActionMetadata{
		Name: "AddUserToProject",
		Type: opent.ActionTypeAuto,
	}
)

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

func NewAddUserToProject(comps *actions.Components) actions.AutoAction {
	return &addUserToProject{comps: comps}
}

func (a *addUserToProject) Metadata() opent.ActionMetadata {
	return ActionAddUserToProject
}

func (a *addUserToProject) 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 *addUserToProject) Start(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	oid, pid, uid, role, err := a.getParam(instance)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}
	err = a.comps.TenantAPI.AddUserToProject(ctx, oid, pid, uid, role, instance.Applicant)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}

	return actions.SucceededActionResult(nil), nil
}

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

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

	pid, err := actions.GetProjectIDStr(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, pid, uid, role, nil
}
