package mail

import (
	"github.com/tech/sendico/notification/interface/api/localizer"
	mmail "github.com/tech/sendico/notification/internal/server/notificationimp/mail/messagebuilder"
	"github.com/tech/sendico/pkg/domainprovider"
	"github.com/tech/sendico/pkg/messaging"
	nn "github.com/tech/sendico/pkg/messaging/notifications/notification"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"go.uber.org/zap"
)

type AmpliMailer struct {
	logger   mlogger.Logger
	producer messaging.Producer
	client   Client
	source   string
}

func (am *AmpliMailer) Send(m mmail.MailBuilder) error {
	err := am.client.Send(m)
	if err != nil {
		am.logger.Warn("Failed to send email", zap.Error(err))
	}
	opResult := model.OperationResult{
		IsSuccessful: err == nil,
	}
	if !opResult.IsSuccessful {
		opResult.Error = err.Error()
	}
	msg, e := m.Build()
	if e != nil {
		am.logger.Warn("Failed to build message content", zap.Error(e))
		return e
	}
	if er := am.producer.SendMessage(nn.NotificationSent(am.source, &model.NotificationResult{
		Channel:    "email",
		TemplateID: msg.TemplateID(),
		Locale:     msg.Locale(),
		AmpliEvent: model.AmpliEvent{
			UserID: "",
		},
		Result: opResult,
	})); er != nil {
		am.logger.Warn("Failed to send mailing result", zap.Error(er))
	}
	return err
}

func (am *AmpliMailer) MailBuilder() mmail.MailBuilder {
	return am.client.MailBuilder()
}

func NewAmpliMailer(log mlogger.Logger, sender string, producer messaging.Producer, l localizer.Localizer, dp domainprovider.DomainProvider, config *Config) (*AmpliMailer, error) {
	logger := log.Named("ampli")
	c, err := createMailClient(logger, producer, l, dp, config)
	if err != nil {
		logger.Warn("Failed to create mailng driver", zap.Error(err), zap.String("driver", config.Driver))
		return nil, err
	}
	am := &AmpliMailer{
		logger:   logger,
		client:   c,
		producer: producer,
		source:   sender,
	}
	am.logger.Info("Amplitude wrapper installed")
	return am, nil
}
