package internal

import (
	"context"
	"encoding/json"
	"io"

	api "git.vdhsn.com/barretthousen/barretthousen/src/catalog/api"
	"git.vdhsn.com/barretthousen/barretthousen/src/catalog/internal/domain"
	"git.vdhsn.com/barretthousen/barretthousen/src/lib/kernel"
)

type KafkaConsumer interface {
	io.Closer
	ConsumeAsync(context.Context, chan<- []byte)
}

type AuctionImporter interface {
	ImportAuction(context.Context, domain.ImportAuctionMessage) (domain.AuctionCreated, error)
}

func RunIndexer(ctx context.Context, c KafkaConsumer, importer AuctionImporter) {
	defer c.Close()

	msgs := make(chan []byte, 64)
	go c.ConsumeAsync(ctx, msgs)

	for msg := range msgs {
		var auction api.Auction
		if err := json.Unmarshal(msg, &auction); err != nil {
			kernel.TraceLog.Printf("could not ingest: %w", err)
			continue
		}

		_, err := importer.ImportAuction(ctx, domain.ImportAuctionMessage{
			Auction: domain.Auction{
				ItemCount:      auction.ItemCount,
				Start:          auction.Start,
				End:            auction.End,
				Title:          auction.Title,
				Description:    auction.Description,
				SourceSiteURL:  auction.Source.SiteURL,
				SourceSiteName: auction.Source.Name,
				SourceURL:      auction.Source.AuctionURL,
				Country:        auction.Address.CountryCode,
				Province:       auction.Address.State,
			},
		})
		if err != nil {
			kernel.ErrorLog.Printf("could not import auction: %w", err)
			continue
		}

	}
}
