package notifications

import (
	"context"
	"encoding/json"

	me "github.com/tech/sendico/pkg/messaging/envelope"
	np "github.com/tech/sendico/pkg/messaging/notifications/processor"
	ch "github.com/tech/sendico/pkg/messaging/notifications/telegram/handler"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"go.uber.org/zap"
)

type TelegramReactionProcessor struct {
	logger  mlogger.Logger
	handler ch.TelegramReactionHandler
	event   model.NotificationEvent
}

func (trp *TelegramReactionProcessor) Process(ctx context.Context, envelope me.Envelope) error {
	var msg model.TelegramReactionRequest
	if err := json.Unmarshal(envelope.GetData(), &msg); err != nil {
		trp.logger.Warn("Failed to decode telegram reaction envelope", zap.Error(err), zap.String("topic", trp.event.ToString()))
		return err
	}
	if trp.handler == nil {
		trp.logger.Warn("Telegram reaction handler is not configured", zap.String("topic", trp.event.ToString()))
		return nil
	}
	return trp.handler(ctx, &msg)
}

func (trp *TelegramReactionProcessor) GetSubject() model.NotificationEvent {
	return trp.event
}

func NewTelegramReactionProcessor(logger mlogger.Logger, handler ch.TelegramReactionHandler) np.EnvelopeProcessor {
	if logger != nil {
		logger = logger.Named("telegram_reaction_processor")
	}
	return &TelegramReactionProcessor{
		logger:  logger,
		handler: handler,
		event:   telegramReactionEvent(),
	}
}
