package notifications

import (
	"context"
	"encoding/json"
	"strings"

	me "github.com/tech/sendico/pkg/messaging/envelope"
	ch "github.com/tech/sendico/pkg/messaging/notifications/paymentorchestrator/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"
)

type PaymentStatusUpdatedProcessor struct {
	logger  mlogger.Logger
	handler ch.PaymentStatusUpdatedHandler
	event   model.NotificationEvent
}

func (p *PaymentStatusUpdatedProcessor) Process(ctx context.Context, envelope me.Envelope) error {
	var msg model.PaymentStatusUpdated
	if err := json.Unmarshal(envelope.GetData(), &msg); err != nil {
		p.logger.Warn("Failed to decode payment status updated envelope", zap.Error(err), zap.String("topic", p.event.ToString()))
		return err
	}
	if strings.TrimSpace(msg.Type) == "" {
		msg.Type = model.PaymentStatusUpdatedType
	}
	if p.handler == nil {
		p.logger.Warn("Payment status updated handler is not configured", zap.String("topic", p.event.ToString()))
		return nil
	}
	return p.handler(ctx, &msg)
}

func (p *PaymentStatusUpdatedProcessor) GetSubject() model.NotificationEvent {
	return p.event
}

func NewPaymentStatusUpdatedProcessor(logger mlogger.Logger, handler ch.PaymentStatusUpdatedHandler) np.EnvelopeProcessor {
	if logger != nil {
		logger = logger.Named("payment_status_updated_processor")
	}
	return &PaymentStatusUpdatedProcessor{
		logger:  logger,
		handler: handler,
		event:   paymentStatusUpdatedEvent(),
	}
}
