package services

import (
	"context"
	"sync"

	"github.com/fiskerinc/cloud-services/pkg/kafka"
	"github.com/fiskerinc/cloud-services/pkg/logger"
)

var producer kafka.ProducerInterface
var producerOnce sync.Once

// GetKafkaProducer returns singleton instance of kafka producer
func GetKafkaProducer() kafka.ProducerInterface {
	producerOnce.Do(func() {
		if producer != nil {
			return
		}
		ctx := context.Background()
		var err error
		producer, err = kafka.NewProducer(ctx)
		if err != nil {
			logger.Error().Err(err).Send()
		}
		go producer.ReadEvents()
	})

	return producer
}

func SetKafkaProducer(p kafka.ProducerInterface) {
	producer = p
}
