package card_info_apple

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

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

	v1 "kami/api/card_info_apple/v1"

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

func (c *ControllerV1) CallBackOrderManual(ctx context.Context, req *v1.CallBackOrderManualReq) (res *v1.CallBackOrderManualRes, err error) {
	rechargeOrderService := service.AppleOrder()
	orderEntity, err := rechargeOrderService.GetOneByOrderNo(ctx, req.OrderNo, nil, req.ID)
	if err != nil || orderEntity.Id == 0 {
		err = gerror.NewCode(gcode.CodeOperationFailed, "订单不存在")
		return
	}
	if orderEntity.Status != int(consts.AppleRechargeOrderSuccess) &&
		orderEntity.Status != int(consts.AppleRechargeOrderFail) {
		err = gerror.NewCode(gcode.CodeInvalidRequest, "订单正在处理中，请稍后重试~")
		_ = rechargeOrderService.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
			OrderNo:     orderEntity.OrderNo,
			RechargeId:  int(orderEntity.Id),
			AccountID:   orderEntity.AccountId,
			AccountName: orderEntity.AccountName,
			Operation:   consts.AppleRechargeOperationCallBackHandling,
		}, nil)
		return
	}
	_ = rechargeOrderService.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
		OrderNo:     orderEntity.OrderNo,
		RechargeId:  int(orderEntity.Id),
		AccountID:   orderEntity.AccountId,
		AccountName: orderEntity.AccountName,
		Operation:   consts.AppleRechargeOperationHandleSuccessByManual,
	}, nil)
	err = rechargeOrderService.CallBackOrderToUpstream(ctx, req.OrderNo)
	if err != nil {
		err = errHandler.WrapError(ctx, errHandler.CornError, err, "回调网关失败，请稍后重试~")
		return
	}
	return
}
