package port

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

type EnnoblementWatermillConsumer struct {
	svc          *app.EnnoblementService
	subscriber   message.Subscriber
	logger       watermill.LoggerAdapter
	marshaler    watermillmsg.Marshaler
	cmdSyncTopic string
}

func NewEnnoblementWatermillConsumer(
	svc *app.EnnoblementService,
	subscriber message.Subscriber,
	logger watermill.LoggerAdapter,
	marshaler watermillmsg.Marshaler,
	cmdSyncTopic string,
) *EnnoblementWatermillConsumer {
	return &EnnoblementWatermillConsumer{
		svc:          svc,
		subscriber:   subscriber,
		logger:       logger,
		marshaler:    marshaler,
		cmdSyncTopic: cmdSyncTopic,
	}
}

func (c *EnnoblementWatermillConsumer) Register(router *message.Router) {
	router.AddNoPublisherHandler(
		"EnnoblementConsumer.sync",
		c.cmdSyncTopic,
		c.subscriber,
		c.sync,
	)
}

func (c *EnnoblementWatermillConsumer) sync(msg *message.Message) error {
	var rawPayload watermillmsg.SyncEnnoblementsCmdPayload

	if err := c.marshaler.Unmarshal(msg, &rawPayload); err != nil {
		c.logger.Error("couldn't unmarshal payload", err, watermill.LogFields{
			"handler": message.HandlerNameFromCtx(msg.Context()),
		})
		return nil
	}

	payload, err := domain.NewSyncEnnoblementsCmdPayload(
		rawPayload.ServerKey,
		rawPayload.ServerURL,
		rawPayload.VersionCode,
	)
	if err != nil {
		c.logger.Error("couldn't construct domain.SyncEnnoblementsCmdPayload", err, watermill.LogFields{
			"handler": message.HandlerNameFromCtx(msg.Context()),
		})
		return nil
	}

	return c.svc.Sync(msg.Context(), payload)
}
