package http

import (
	"net/http"

	"quyun/app/jobs"
	"quyun/providers/job"
	"quyun/providers/wepay"

	"github.com/go-pay/gopay/wechat/v3"
	"github.com/gofiber/fiber/v3"
	log "github.com/sirupsen/logrus"
)

// @provider
type pays struct {
	wepay *wepay.Client
	job   *job.Job
}

// Callback
//
//	@Router	/pay/callback/:channel [post]
//	@Bind	channel path
func (ctl *pays) Callback(ctx fiber.Ctx, channel string) error {
	log := log.WithField("method", "pays.Callback")
	return ctl.wepay.ParseNotify(
		ctx,
		func(ctx fiber.Ctx, notify *wechat.V3DecryptPayResult) error {
			if err := ctl.job.Add(&jobs.WechatPayNotify{Notify: notify}); err != nil {
				log.Errorf("add job error:%v", err)
				return ctx.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to add job"})
			}
			return nil
		},
		func(c fiber.Ctx, notify *wechat.V3DecryptRefundResult) error {
			if err := ctl.job.Add(&jobs.WechatRefundNotify{Notify: notify}); err != nil {
				log.Errorf("add job error:%v", err)
				return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to add job"})
			}
			return nil
		},
	)
}
