package kafka

import (
	"context"
	"errors"
	"io"

	"git.vdhsn.com/barretthousen/barretthousen/src/lib/kernel"
	kafka "github.com/segmentio/kafka-go"
)

type kafkaConsumer struct {
	*kafka.Conn
}

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

func (c *kafkaConsumer) ConsumeAsync(ctx context.Context, output chan<- []byte) {
	for {

		batch := c.ReadBatch(1024, 1024*50)

		for {
			msg, err := batch.ReadMessage()
			if err != nil && !errors.Is(err, io.EOF) || len(msg.Value) == 0 {
				break
			}
			kernel.TraceLog.Printf("header: %+v, value: %+v", msg.Headers, msg.Value)

			select {
			case output <- msg.Value:
			case <-ctx.Done():
				batch.Close()
				return
			}

		}

		batch.Close()
		select {
		case <-ctx.Done():
			return
		}
	}
}

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

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