package reward

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/util"
)

func AdminBalanceOperate(req models.AdminRewardOperateReq, doer *models.User) error {
	logId := util.UUID()
	_, err := models.InsertRewardAdminLog(&models.RewardAdminLog{
		LogId:        logId,
		Amount:       req.Amount,
		RewardType:   req.RewardType.Name(),
		TargetUserId: req.TargetUserId,
		CreatorId:    doer.ID,
		CreatorName:  doer.Name,
		Remark:       req.Remark,
		Status:       models.RewardAdminLogProcessing,
	})
	if err != nil {
		log.Error("AdminBalanceOperate InsertRewardAdminLog error.%v", err)
		return err
	}

	//reward
	err = Operate(&models.RewardOperateContext{
		SourceType: models.SourceTypeAdminOperate,
		SourceId:   logId,
		Title:      "管理员操作",
		Reward: models.Reward{
			Amount: req.Amount,
			Type:   req.RewardType,
		},
		TargetUserId:      req.TargetUserId,
		RequestId:         logId,
		OperateType:       req.OperateType,
		Remark:            req.Remark,
		RejectPolicy:      models.JustReject,
		PermittedNegative: true,
	})

	if err != nil {
		log.Error("AdminBalanceOperate operate error.%v", err)
		models.UpdateRewardAdminLogStatus(logId, models.RewardAdminLogProcessing, models.RewardAdminLogFailed)
		return err
	}
	models.UpdateRewardAdminLogStatus(logId, models.RewardAdminLogProcessing, models.RewardAdminLogSuccess)
	return nil
}
