package notifications

import (
	"context"

	gmessaging "github.com/tech/sendico/pkg/generated/gmessaging"
	me "github.com/tech/sendico/pkg/messaging/envelope"
	nh "github.com/tech/sendico/pkg/messaging/notifications/notification/handler"
	np "github.com/tech/sendico/pkg/messaging/notifications/processor"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"go.uber.org/zap"
	"google.golang.org/protobuf/proto"
)

type NResultNotificaionProcessor struct {
	logger  mlogger.Logger
	handler nh.NResultHandler
	event   model.NotificationEvent
}

func (nrp *NResultNotificaionProcessor) Process(ctx context.Context, envelope me.Envelope) error {
	var msg gmessaging.NotificationSentEvent
	if err := proto.Unmarshal(envelope.GetData(), &msg); err != nil {
		nrp.logger.Warn("Failed to unmarshall envelope", zap.Error(err), zap.String("topic", nrp.event.ToString()))
		return err
	}
	nresult := &model.NotificationResult{
		AmpliEvent: model.AmpliEvent{
			UserID: msg.UserId,
		},
		Channel:    msg.Channel,
		TemplateID: msg.TemplateId,
		Locale:     msg.Locale,
		Result: model.OperationResult{
			IsSuccessful: msg.Status.IsSuccessful,
			Error:        msg.Status.ErrorDescription,
		},
	}
	return nrp.handler(ctx, nresult)
}

func (nrp *NResultNotificaionProcessor) GetSubject() model.NotificationEvent {
	return nrp.event
}

func NewAccountMessageProcessor(logger mlogger.Logger, handler nh.NResultHandler) np.EnvelopeProcessor {
	return &NResultNotificaionProcessor{
		logger:  logger.Named("message_processor"),
		handler: handler,
		event:   NewNRNotification(),
	}
}
