package services

import (
	"context"
	"sync"

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

const serviceName = "optimus"

var consumer kafka.ConsumerInterface
var consumerOnce sync.Once

// GetKafkaConsumer returns singleton instance of kafka consumer
func GetKafkaConsumer() (kafka.ConsumerInterface, error) {
	var err error

	consumerOnce.Do(func() {
		consumer, err = kafka.NewConsumer(serviceName)
		if err != nil {
			logger.Error().Err(err).Send()
		}
	})
	if err != nil {
		return nil, err
	}

	return consumer, nil
}

var producer kafka.ProducerInterface
var producerOnce sync.Once

// GetKafkaProducer returns singleton instance of kafka producer
func GetKafkaProducer() (kafka.ProducerInterface, error) {
	var err error

	producerOnce.Do(func() {
		ctx := context.Background()
		producer, err = kafka.NewAsyncProducer(ctx)
		if err != nil {
			logger.Error().Err(err).Send()
		}
		go producer.ReadEvents()
	})
	if err != nil {
		return nil, err
	}

	return producer, nil
}
