package adapter

import (
	"context"
	"fmt"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
	"gitea.dwysokinski.me/twhelp/corev3/internal/watermill/watermillmsg"
	"github.com/ThreeDotsLabs/watermill/message"
)

type TribeWatermillPublisher struct {
	marshaler        watermillmsg.Marshaler
	publisher        message.Publisher
	eventSyncedTopic string
}

func NewTribeWatermillPublisher(
	publisher message.Publisher,
	marshaler watermillmsg.Marshaler,
	eventSyncedTopic string,
) *TribeWatermillPublisher {
	return &TribeWatermillPublisher{
		publisher:        publisher,
		marshaler:        marshaler,
		eventSyncedTopic: eventSyncedTopic,
	}
}

func (pub *TribeWatermillPublisher) EventSynced(
	ctx context.Context,
	payloads ...domain.TribesSyncedEventPayload,
) error {
	msgs := make([]*message.Message, 0, len(payloads))

	for _, p := range payloads {
		msg, err := pub.marshaler.Marshal(ctx, watermillmsg.TribesSyncedEventPayload{
			ServerKey:   p.ServerKey(),
			VersionCode: p.VersionCode(),
			ServerURL:   p.ServerURL(),
			NumTribes:   p.NumTribes(),
		})
		if err != nil {
			return fmt.Errorf("%s: couldn't marshal TribesSyncedEventPayload: %w", p.ServerKey(), err)
		}

		msgs = append(msgs, msg)
	}

	if err := pub.publisher.Publish(pub.eventSyncedTopic, msgs...); err != nil {
		return fmt.Errorf("couldn't publish message to topic '%s': %w", pub.eventSyncedTopic, err)
	}

	return nil
}
