package operation

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/tidbcloud/devops/api"
	opapi "github.com/tidbcloud/devops/api/operation"
	"github.com/tidbcloud/devops/entity/operation"
	ctrl "github.com/tidbcloud/devops/pkg/controller"
)

// ListActions
//
//	@Id				OperationControllerListActions
//	@Description	list actions
//	@Tags			OperationController
//	@Accept			json
//	@Produce		json
//	@Param			req	query		opapi.ListActionReq	false	"request param"
//	@Success		200	{object}	opapi.ListActionResp
//	@Router			/api/v1/devops/operation/actions [get]
func (c *OperationController) ListActions(ctx *gin.Context) {
	req := &opapi.ListActionReq{}
	err := ctx.ShouldBindQuery(req)
	if err != nil {
		ctrl.FailWithCode(ctx, err, api.ErrCodeInvalidArgument)
		return
	}

	actions, err := c.opSvc.ListActions(ctx)
	if err != nil {
		ctrl.Fail(ctx, err)
		return
	}

	resp := &opapi.ListActionResp{
		Total:   int64(len(actions)),
		Actions: actions,
	}
	ctrl.Success(ctx, resp)
}

// GetAction
//
//	@Id				OperationControllerGetAction
//	@Description	get a action
//	@Tags			OperationController
//	@Accept			json
//	@Produce		json
//	@Param			action_name	path		string	true	"action name"
//	@Success		200			{object}	opapi.GetActionResp
//	@Router			/api/v1/devops/operation/actions/{action_name} [get]
func (c *OperationController) GetAction(ctx *gin.Context) {
	name := ctx.Param("action_name")
	if name == "" {
		ctrl.FailWithCode(ctx, fmt.Errorf("name is required"), api.ErrCodeInvalidArgument)
		return
	}

	act, err := c.opSvc.GetAction(ctx, operation.ActionName(name))
	if err != nil {
		ctrl.Fail(ctx, err)
		return
	}

	resp := &opapi.GetActionResp{Action: act}
	ctrl.Success(ctx, resp)
}
