package wepay

import (
	"context"
	"fmt"
	"testing"
	"time"

	"quyun/app/service/testx"

	"github.com/go-pay/gopay/wechat/v3"
	"github.com/go-pay/util/js"
	. "github.com/smartystreets/goconvey/convey"
	"github.com/stretchr/testify/suite"
	"go.ipao.vip/atom/contracts"
	"go.uber.org/dig"
)

type WePayInjectParams struct {
	dig.In
	Initials []contracts.Initial `group:"initials"`

	Client *Client
}

type WePayTestSuite struct {
	suite.Suite

	WePayInjectParams
}

func Test_WePay(t *testing.T) {
	providers := testx.Default().With(Provide)
	testx.Serve(providers, t, func(params WePayInjectParams) {
		suite.Run(t, &WePayTestSuite{WePayInjectParams: params})
	})
}

func (s *WePayTestSuite) Test_PrePay() {
	Convey("get prepay", s.T(), func() {
		Convey("prepay", func() {
			resp, err := s.Client.V3TransactionJsapi(context.Background(), func(bm *BodyMap) {
				bm.
					OutTradeNo(fmt.Sprintf("test_trade_no_%d", time.Now().Unix())).
					Description("Test transaction").
					Payer("o5Bzk644x3LOMJsKSZRlqWin74IU")
			})
			So(err, ShouldBeNil)
			So(resp, ShouldNotBeNil)
			s.T().Logf("prepay response: %+v", resp)

			sign, err := resp.PaySignOfJSAPI()
			So(err, ShouldBeNil)
			s.T().Logf("Sign: %+v", sign)
		})
	})
}

func (s *WePayTestSuite) Test_parseNotify() {
	Convey("parse notify", s.T(), func() {
		Convey("prepay", func() {
			content := `{"id":"43d17a94-eb1e-5641-bb11-f59e5b6e8749","summary":"支付成功","resource":{"nonce":"avbpSc2seCN5","algorithm":"AEAD_AES_256_GCM","ciphertext":"20VGA2uItmbqFvGBxBug2K3eORRyy/xYswoDA7v4+Yi2ArHnXCXzScVn6kD3ZVpKLiFY7zcTPpTxk2JFJF3vG/6WGG7uuD8DDK7keJk0PZoAfvmSPskQzieOVz3Tgmqp3SkE74mJHX1MeMZHMXMmzMJ4Mp1OmYD2YpiWsF7jlAtiGqxHSC//YlKGaJ/9r0QG4TwZcFpm+X4qkdBNX+DcSCjYeXGyWIm2bVujj63rO43DEA5x0nytdBSrpup/T85khZzNVue1EcyF5XY7PguePU3Q2o+e1c/LnoL9nN7S+n2ljm+nN3uCAhz8eqkPn4uowiq37Tw4JZ2rx2rXCb9jYKmt+I8JHpOij4SgX6oQd7fLeZHsbHC/05s0A1qdLzeF5AKgrAOQT/T1yQ+LsWTnY2ftXAP6mnqGE8Z+vQm5PGo8xsQ8AycVaAhwaRLFvn/XtwlkumfuduAojimFRSNElWwHcApnT+ekqzBrKnAvKo8hdeygf9QWHENcNWVwqwjUWIHe/fGWgJbc6u595bEHb4MkcI8ESD/6bpay/Wk6SyvZCJHqS1WWaPaU0xh9","original_type":"transaction","associated_data":"transaction"},"event_type":"TRANSACTION.SUCCESS","create_time":"2025-04-30T19:25:51+08:00","resource_type":"encrypt-resource"}`
			var notifyReq wechat.V3NotifyReq
			err := js.UnmarshalBytes([]byte(content), &notifyReq)
			So(err, ShouldBeNil)

			s.T().Logf("notifyReq: %+v", notifyReq)

			var obj struct{}
			err = notifyReq.DecryptCipherTextToStruct("5UBDkxVDY44AKafkqN6YgYxgtkXP6Mw6", &obj)
			So(err, ShouldBeNil)

			s.T().Logf("Decrypted object: %+v", obj)
		})
	})
}
