package jobs

import (
	"context"
	"time"

	"quyun/app/models"
	"quyun/database/fields"

	"github.com/go-pay/gopay/wechat/v3"
	"github.com/pkg/errors"
	. "github.com/riverqueue/river"
	log "github.com/sirupsen/logrus"
	_ "go.ipao.vip/atom"
	"go.ipao.vip/atom/contracts"
	_ "go.ipao.vip/atom/contracts"
)

var _ contracts.JobArgs = (*WechatRefundNotify)(nil)

type WechatRefundNotify struct {
	Notify *wechat.V3DecryptRefundResult `json:"notify"`
}

func (s WechatRefundNotify) InsertOpts() InsertOpts {
	return InsertOpts{
		Queue:    QueueDefault,
		Priority: PriorityDefault,
	}
}

func (WechatRefundNotify) Kind() string       { return "wechat_refund_notify" }
func (a WechatRefundNotify) UniqueID() string { return a.Kind() }

var _ Worker[WechatRefundNotify] = (*WechatRefundNotifyWorker)(nil)

// @provider(job)
type WechatRefundNotifyWorker struct {
	WorkerDefaults[WechatRefundNotify]
}

func (w *WechatRefundNotifyWorker) Work(ctx context.Context, job *Job[WechatRefundNotify]) error {
	log := log.WithField("job", job.Args.Kind())

	log.Infof("[Start] Working on job with strings: %+v", job.Args)
	defer log.Infof("[End] Finished %s", job.Args.Kind())

	notify := job.Args.Notify

	order, err := models.Orders.GetByOrderNo(context.Background(), notify.OutTradeNo)
	if err != nil {
		log.Errorf("GetByOrderNo error:%v", err)
		return err
	}

	meta := order.Meta.Data
	meta.RefundNotify = notify
	order.Status = fields.OrderStatusRefundProcessing
	switch notify.RefundStatus {
	case "SUCCESS":
		order.Status = fields.OrderStatusRefundSuccess
	case "CLOSED":
		order.Status = fields.OrderStatusRefundClosed
	case "PROCESSING":
		order.Status = fields.OrderStatusRefundProcessing
	case "ABNORMAL":
		order.Status = fields.OrderStatusRefundAbnormal
	}
	order.Meta = fields.ToJson(meta)

	log.Infof("Updated order details: %+v", order)
	tx, err := models.Transaction(ctx)
	if err != nil {
		return errors.Wrap(err, "Transaction error")
	}
	defer tx.Rollback()

	if order.Status == fields.OrderStatusRefundSuccess {
		if err := models.Users.RevokePosts(context.Background(), order.UserID, order.PostID); err != nil {
			log.Errorf("RevokePosts error:%v", err)
			return errors.Wrap(err, "RevokePosts error")
		}
	}

	if err := models.Orders.Update(context.Background(), order); err != nil {
		log.Errorf("Update order error:%v", err)
		return errors.Wrap(err, "Update order error")
	}
	if err := tx.Commit(); err != nil {
		log.Errorf("Commit error:%v", err)
		return errors.Wrap(err, "Commit error")
	}

	log.Infof("Successfully processed order %s", notify.OutTradeNo)
	return nil
}

func (w *WechatRefundNotifyWorker) NextRetry(job *Job[WechatRefundNotify]) time.Time {
	return time.Now().Add(30 * time.Second)
}
