package ingesters

import (
	"context"
	"encoding/json"

	"github.com/deepfence/ThreatMapper/deepfence_utils/directory"
	"github.com/deepfence/ThreatMapper/deepfence_utils/log"
	"github.com/deepfence/ThreatMapper/deepfence_utils/utils"
	ingestersUtil "github.com/deepfence/ThreatMapper/deepfence_utils/utils/ingesters"
	"github.com/twmb/franz-go/pkg/kgo"
)

type MalwareIngester struct{}

func NewMalwareIngester() KafkaIngester[[]map[string]interface{}] {
	return &MalwareIngester{}
}

func (tc *MalwareIngester) Ingest(
	ctx context.Context,
	cs []map[string]interface{},
	ingestC chan *kgo.Record,
) error {
	tenantID, err := directory.ExtractNamespace(ctx)
	if err != nil {
		return err
	}

	rh := []kgo.RecordHeader{
		{Key: "namespace", Value: []byte(tenantID)},
	}

	for _, c := range cs {
		cb, err := json.Marshal(c)
		if err != nil {
			log.Error().Msg(err.Error())
		} else {
			ingestC <- &kgo.Record{
				Topic:   utils.TopicWithNamespace(utils.MalwareScan, string(tenantID)),
				Value:   cb,
				Headers: rh,
			}
		}
	}

	return nil
}

type MalwareScanStatusIngester struct{}

func NewMalwareScanStatusIngester() KafkaIngester[[]ingestersUtil.MalwareScanStatus] {
	return &MalwareScanStatusIngester{}
}

func (tc *MalwareScanStatusIngester) Ingest(
	ctx context.Context,
	statuses []ingestersUtil.MalwareScanStatus,
	ingestC chan *kgo.Record,
) error {
	tenantID, err := directory.ExtractNamespace(ctx)
	if err != nil {
		return err
	}

	rh := []kgo.RecordHeader{
		{Key: "namespace", Value: []byte(tenantID)},
	}

	for _, c := range statuses {
		cb, err := json.Marshal(c)
		if err != nil {
			log.Error().Msg(err.Error())
		} else {
			ingestC <- &kgo.Record{
				Topic:   utils.TopicWithNamespace(utils.MalwareScanStatus, string(tenantID)),
				Value:   cb,
				Headers: rh,
			}
		}
	}

	return nil
}
