package webhooks

import (
	"context"
	"encoding/json"
	"net/http"
	"time"

	"github.com/operator/command-center/internal/eventbus"
)

// GenericHandler accepts any JSON body, decodes it to a map[string]any, and
// publishes on TopicWebhookCustom. Operators wire custom scripts or
// third-party tools via this handler when no per-source handler exists.
type GenericHandler struct {
	Bus *eventbus.Bus
}

func (h *GenericHandler) HandlerType() string { return "generic" }

func (h *GenericHandler) Handle(ctx context.Context, r *http.Request, body []byte, endpointID string) error {
	var m map[string]any
	if err := json.Unmarshal(body, &m); err != nil {
		// Treat non-JSON bodies as a single "raw" field so the operator's
		// downstream subscriber can still see the payload.
		m = map[string]any{"raw": string(body)}
	}
	if h.Bus != nil {
		h.Bus.Publish(eventbus.Event{
			Topic: eventbus.TopicWebhookCustom,
			Payload: CustomEvent{
				EndpointID: endpointID,
				Payload:    m,
				ReceivedAt: time.Now(),
			},
		})
	}
	return nil
}
