package services

import (
	"context"
	"sync"

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

const serviceName = "attendant"
const oldServiceName = "old-attendant"

var consumer, oldConsumer kafka.ConsumerInterface
var consumerOnce sync.Once

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

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

	return consumer, oldConsumer, nil
}

var producer kafka.ProducerInterface
var producerOnce sync.Once

func GetKafkaProducer() (kafka.ProducerInterface, error) {
	var err error
	producerOnce.Do(func() {
		if producer == nil {
			var producerTemp kafka.ProducerInterface
			producerTemp, err = kafka.NewProducer(context.Background())
			if err != nil {
				logger.Err(err).Send()
			}
			producer = producerTemp
		}
	})

	if err != nil {
		return nil, err
	}
	return producer, err
}

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