package kafka

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	kafka "github.com/segmentio/kafka-go"
)

type kafkaProducer struct {
	*kafka.Conn
}

func (c *kafkaProducer) Close() error {
	return c.Conn.Close()
}

func (c *kafkaProducer) SendMessageJSON(headers map[string]string, msg interface{}) (err error) {
	var data []byte
	if data, err = json.Marshal(msg); err != nil {
		err = fmt.Errorf("could not marshal message into JSON: %w", err)
		return
	}
	h := []kafka.Header{}

	for k, v := range headers {
		h = append(h, kafka.Header{
			Key:   k,
			Value: []byte(v),
		})
	}

	if _, err = c.WriteMessages(kafka.Message{
		Time:    time.Now().UTC(),
		Headers: h,
		Value:   data,
	}); err != nil {
		return
	}

	return
}

func NewProducer(topic string) (*kafkaProducer, error) {
	conn, err := kafka.DialLeader(context.Background(), "tcp", "kafka:9092", topic, 0)
	if err != nil {
		return nil, err
	}

	return &kafkaProducer{
		Conn: conn,
	}, nil
}
