package brokers

import (
	"amocrm/internal/models"
	"context"
	"encoding/json"
	"github.com/twmb/franz-go/pkg/kgo"
	"go.uber.org/zap"
)

type ProducerDeps struct {
	KafkaClient *kgo.Client
	Logger      *zap.Logger
}

type Producer struct {
	kafkaClient *kgo.Client
	logger      *zap.Logger
}

func NewProducer(deps ProducerDeps) *Producer {
	return &Producer{
		logger:      deps.Logger,
		kafkaClient: deps.KafkaClient,
	}
}

func (p *Producer) ToKafkaUpdate(ctx context.Context, message models.KafkaMessage) error {
	bytes, err := json.Marshal(message)
	if err != nil {
		p.logger.Error("error marshal message to kafka", zap.Error(err))
		return err
	}

	responses := p.kafkaClient.ProduceSync(ctx, &kgo.Record{Value: bytes})
	for _, response := range responses {
		if response.Err != nil {
			p.logger.Error("failed to send message on update kafka", zap.Error(response.Err))
			return response.Err
		}

	}

	return nil
}
