package service

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"voucher/internal/pkg/rdsmq"
)

func (s *VoucherService) GetUsedNotifyConfig() *rdsmq.ConsumeConfig {

	queue := s.bc.RdsMQ.GetUsedNotify()
	if queue == nil {
		return nil
	}

	if !queue.GetIsOpen() {
		log.Warn(fmt.Sprintf("[%s]RdsMQ is not open", queue.Name))
		return nil
	}

	return &rdsmq.ConsumeConfig{
		Rdb:        s.rdb.Rdb,
		QueueName:  queue.Name,
		NumWorkers: queue.NumWorkers,
		WaitTime:   queue.GetWaitTime().AsDuration(),
		RetryNum:   queue.RetryNum,
		Fn:         s.HandleUsedNotify,
		Logger:     s.logHelper,
	}
}

func (s *VoucherService) HandleUsedNotify(ctx context.Context, msg string) error {

	if msg == "" {
		s.logHelper.Errorf("RdsMQ used notify error: msg is empty")
		return nil
	}

	if err := s.VoucherBiz.UsedNotify(ctx, msg); err != nil {
		s.logHelper.Error(err)
	}

	return nil
}
