package routewatch

import (
	"git.eeqj.de/sneak/routewatch/internal/logger"
	"git.eeqj.de/sneak/routewatch/internal/ristypes"
)

// SimpleHandler is a basic implementation of streamer.MessageHandler that
// filters messages by type and delegates processing to a callback function.
// It provides a simple way to handle specific RIS message types without
// implementing the full MessageHandler interface from scratch.
type SimpleHandler struct {
	logger       *logger.Logger
	messageTypes []string
	callback     func(*ristypes.RISMessage)
}

// NewSimpleHandler creates a new SimpleHandler that accepts specific message types.
// The messageTypes parameter specifies which RIS message types this handler will process.
// If messageTypes is empty, the handler will accept all message types.
// The callback function is invoked for each message that passes the type filter.
func NewSimpleHandler(
	logger *logger.Logger,
	messageTypes []string,
	callback func(*ristypes.RISMessage),
) *SimpleHandler {
	return &SimpleHandler{
		logger:       logger,
		messageTypes: messageTypes,
		callback:     callback,
	}
}

// WantsMessage returns true if this handler wants to process messages of the given type.
// It checks whether messageType is in the handler's configured list of accepted types.
// If no specific types were configured (empty messageTypes slice), it returns true for all types.
func (h *SimpleHandler) WantsMessage(messageType string) bool {
	// If no specific types are set, accept all messages
	if len(h.messageTypes) == 0 {
		return true
	}

	for _, t := range h.messageTypes {
		if t == messageType {
			return true
		}
	}

	return false
}

// HandleMessage processes a RIS message by invoking the configured callback function.
// If no callback was provided during construction, the message is silently ignored.
func (h *SimpleHandler) HandleMessage(msg *ristypes.RISMessage) {
	if h.callback != nil {
		h.callback(msg)
	}
}
