package sys_payment

import (
	"context"
	"fmt"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
	"kami/utility/token"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	"kami/api/sys_payment/v1"
)

func (c *ControllerV1) SysPaymentAdd(ctx context.Context, req *v1.SysPaymentAddReq) (res *v1.SysPaymentAddRes, err error) {
	if !token.IsFromIframe(ctx) {
		return nil, gerror.NewCode(gcode.CodeNotSupported, "权限不足")
	}
	userPaymentService := service.SysUserPayment()
	switch req.TransactionType {
	case consts.UserPaymentRecordStatusRecharge:
		_, err = userPaymentService.Recharge(ctx, model.SysUserPaymentRechargeOrConsumeInput{
			UserId:          req.UserId,
			Amount:          req.Amount,
			Remark:          req.Remark,
			TransactionType: req.TransactionType,
		}, nil)
	case consts.UserPaymentRecordStatusManualAdjustment:
		isEnough, err2 := userPaymentService.CheckAmountEnough(ctx, &model.SysUserPaymentCheckBalanceInput{
			UserId: req.UserId,
			Amount: req.Amount,
		})
		if err2 != nil {
			err = errHandler.WrapError(ctx, gcode.CodeInternalError, err2, "充值/消费失败")
			return
		}
		if !isEnough {
			err = gerror.NewCode(gcode.CodeValidationFailed, "余额不足")
			return
		}
		_, err = userPaymentService.Consumption(ctx, &model.SysUserPaymentRechargeOrConsumeInput{
			UserId:          req.UserId,
			Amount:          req.Amount,
			TransactionType: req.TransactionType,
			Remark:          fmt.Sprintf("人工操作，%s", req.Remark),
		}, nil)
	default:
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "调整余额失败")
	}
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "充值/消费失败")
	}
	return
}
