package card_info_walmart

import (
	"context"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/service"

	"github.com/duke-git/lancet/v2/slice"

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

	"kami/api/card_info_walmart/v1"
)

func (c *ControllerV1) OrderCallback(ctx context.Context, req *v1.OrderCallbackReq) (res *v1.OrderCallbackRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}

	orderInfo, err := service.CardRedeemOrder().GetOrderOneByOrderNo(ctx, req.OrderNo, nil)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "订单不存在")
		return
	}

	if userInfo.Id != "" && orderInfo.CreatedUserId != userInfo.Id {
		err = gerror.NewCode(gcode.CodeNotAuthorized, "权限不足")
		return
	}

	if orderInfo.NotifyStatus == 1 {
		err = gerror.NewCode(gcode.CodeOperationFailed, "订单已经回调")
		return
	}

	if !slice.Contain([]consts.RedeemOrderStatus{consts.RedeemOrderSuccess, consts.RedeemOrderFail}, consts.RedeemOrderStatus(orderInfo.Status)) {
		//开始回调
		err = gerror.NewCode(gcode.CodeOperationFailed, "订单未处于处理结束状态")
		return
	}

	if slice.Contain([]consts.RedeemOrderStatus{consts.RedeemOrderSuccessWithDifferentAmount, consts.RedeemOrderFailWithDifferentAmount}, consts.RedeemOrderStatus(orderInfo.OrderStatus)) {
		//开始回调
		err = gerror.NewCode(gcode.CodeOperationFailed, "金额异议不回调")
	}
	_ = service.CardRedeemOrder().CallBackOrderToUpstream(context.Background(), orderInfo.OrderNo, true)
	return
}
