package kafkaclient

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

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

func Consume[T any](r *kafka.Reader, ch chan<- T, ctx context.Context, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		select {
		case <-ctx.Done():
			fmt.Println("consumer closed")
			return
		default:
			msg, err := r.ReadMessage(ctx)
			if err != nil {
				fmt.Println("error reading message:", err)
				continue
			}

			var data T
			if err := json.Unmarshal(msg.Value, &data); err != nil {
				fmt.Println("error decoding:", err)
				continue
			}

			ch <- data
		}
	}
}
