package cmb

import (
	"context"
	"encoding/json"
	"github.com/go-kratos/kratos/v2/log"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/vo"
)

func (v *Cmb) NotifyRetryConsume(ctx context.Context, order *bo.OrderBo, orderNotify *bo.OrderNotifyBo) (*bo.OrderNotifyBo, error) {

	req := &bo.OrderNotifyBo{
		OrderNo:   orderNotify.OrderNo,
		NotifyUrl: order.NotifyUrl,
		Channel:   order.Channel,
		Event:     orderNotify.Event,
		Type:      order.Type,
		Request:   "",
	}

	request, orderNotify, err := v.notifyCreate(ctx, order, req)
	if err != nil {
		return nil, err
	}

	reply, err := v.CmbMixRepo.Request(ctx, request, order.NotifyUrl)
	if err != nil {
		return orderNotify, v.notifyFail(ctx, orderNotify.ID, err.Error())
	}

	if err = v.CmbMixRepo.VerifyResponse(ctx, reply); err != nil {
		log.Errorf("NotifyRetryConsume CmbMixRepo.VerifyResponse error:%s", err.Error())
		return orderNotify, v.notifyFail(ctx, orderNotify.ID, err.Error())
	}

	if reply.RespCode != vo.CmbResponseStatusSuccess.GetValue() {
		return orderNotify, v.notifyFail(ctx, orderNotify.ID, reply.RespMsg)
	}

	replyJson, _ := json.Marshal(reply)

	return orderNotify, v.notifySuccess(ctx, orderNotify.ID, string(replyJson))
}
