package wechat

import (
	"context"
	"encoding/json"

	"bsm/full/module/finance/wallet/internal/config"
	pb "bsm/full/module/finance/wallet/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"github.com/go-pay/gopay/wechat/v3"
)

// 微信支付回调
func WxCallback(ctx context.Context, in *pb.WxCallBackRequest) (reply *pb.CallBackReply, err error) {
	var notifyReq = &wechat.V3NotifyReq{}
	data, err := json.Marshal(in)
	if err != nil {
		return nil, errcode.ErrJsonMarshal
	}
	err = json.Unmarshal(data, &notifyReq)
	if err != nil {
		return nil, errcode.ErrJsonUnmarshal
	}

	wx, _ := NewWechat()
	pubKey := wx.Client.WxPublicKeyMap()
	err = notifyReq.VerifySignByPKMap(pubKey)
	if err != nil {
		printer.Error(err.Error())
		return &pb.CallBackReply{Code: "FAIL", Message: "验签失败"}, nil
	}
	res, err := notifyReq.DecryptPayCipherText(config.Spec.WeChat.APIV3Key)
	if err != nil {
		printer.Error(err.Error())
		return &pb.CallBackReply{Code: "FAIL", Message: "验签失败"}, err
	}
	// Todo: 业务逻辑
	payResult, _ := json.Marshal(res)
	return &pb.CallBackReply{Code: "SUCCESS", Message: string(payResult)}, nil
}
