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 PlayerWatermillPublisher struct {
	marshaler        watermillmsg.Marshaler
	publisher        message.Publisher
	eventSyncedTopic string
}

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

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

	for _, p := range payloads {
		msg, err := pub.marshaler.Marshal(ctx, watermillmsg.PlayersSyncedEventPayload{
			ServerKey:   p.ServerKey(),
			VersionCode: p.VersionCode(),
			ServerURL:   p.ServerURL(),
			NumPlayers:  p.NumPlayers(),
		})
		if err != nil {
			return fmt.Errorf("%s: couldn't marshal PlayersSyncedEventPayload: %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
}
