package notifications

import (
	"context"

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

type DemoRequestProcessor struct {
	logger  mlogger.Logger
	handler handler.DemoRequestHandler
	event   model.NotificationEvent
}

func (drp *DemoRequestProcessor) Process(ctx context.Context, envelope me.Envelope) error {
	var msg gmessaging.DemoRequestEvent
	if err := proto.Unmarshal(envelope.GetData(), &msg); err != nil {
		drp.logger.Warn("Failed to decode demo request envelope", zap.Error(err), zap.String("topic", drp.event.ToString()))
		return err
	}
	request := &model.DemoRequest{
		Name:             msg.GetName(),
		OrganizationName: msg.GetOrganizationName(),
		Phone:            msg.GetPhone(),
		WorkEmail:        msg.GetWorkEmail(),
		PayoutVolume:     msg.GetPayoutVolume(),
		Comment:          msg.GetComment(),
	}
	return drp.handler(ctx, request)
}

func (drp *DemoRequestProcessor) GetSubject() model.NotificationEvent {
	return drp.event
}

func NewDemoRequestProcessor(logger mlogger.Logger, handler handler.DemoRequestHandler) np.EnvelopeProcessor {
	return &DemoRequestProcessor{
		logger:  logger.Named("demo_request_processor"),
		handler: handler,
		event:   internalsite.NewDemoRequestEvent(),
	}
}
