package notifications

import (
	"context"
	"encoding/json"

	me "github.com/tech/sendico/pkg/messaging/envelope"
	ch "github.com/tech/sendico/pkg/messaging/notifications/paymentgateway/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 PaymentGatewayIntentProcessor struct {
	logger  mlogger.Logger
	handler ch.PaymentGatewayIntentHandler
	event   model.NotificationEvent
}

func (pgp *PaymentGatewayIntentProcessor) Process(ctx context.Context, envelope me.Envelope) error {
	var msg model.PaymentGatewayIntent
	if err := json.Unmarshal(envelope.GetData(), &msg); err != nil {
		pgp.logger.Warn("Failed to decode payment gateway intent envelope", zap.Error(err), zap.String("topic", pgp.event.ToString()))
		return err
	}
	if pgp.handler == nil {
		pgp.logger.Warn("Payment gateway intent handler is not configured", zap.String("topic", pgp.event.ToString()))
		return nil
	}
	return pgp.handler(ctx, &msg)
}

func (pgp *PaymentGatewayIntentProcessor) GetSubject() model.NotificationEvent {
	return pgp.event
}

type PaymentGatewayExecutionProcessor struct {
	logger  mlogger.Logger
	handler ch.PaymentGatewayExecutionHandler
	event   model.NotificationEvent
}

func (pgp *PaymentGatewayExecutionProcessor) Process(ctx context.Context, envelope me.Envelope) error {
	var msg model.PaymentGatewayExecution
	if err := json.Unmarshal(envelope.GetData(), &msg); err != nil {
		pgp.logger.Warn("Failed to decode payment gateway execution envelope", zap.Error(err), zap.String("topic", pgp.event.ToString()))
		return err
	}
	if pgp.handler == nil {
		pgp.logger.Warn("Payment gateway execution handler is not configured", zap.String("topic", pgp.event.ToString()))
		return nil
	}
	return pgp.handler(ctx, &msg)
}

func (pgp *PaymentGatewayExecutionProcessor) GetSubject() model.NotificationEvent {
	return pgp.event
}

func NewPaymentGatewayIntentProcessor(logger mlogger.Logger, handler ch.PaymentGatewayIntentHandler) np.EnvelopeProcessor {
	if logger != nil {
		logger = logger.Named("payment_gateway_intent_processor")
	}
	return &PaymentGatewayIntentProcessor{
		logger:  logger,
		handler: handler,
		event:   intentEvent(),
	}
}

func NewPaymentGatewayExecutionProcessor(logger mlogger.Logger, handler ch.PaymentGatewayExecutionHandler) np.EnvelopeProcessor {
	if logger != nil {
		logger = logger.Named("payment_gateway_execution_processor")
	}
	return &PaymentGatewayExecutionProcessor{
		logger:  logger,
		handler: handler,
		event:   executionEvent(),
	}
}
