package mattermost

import (
	"context"
	"strings"

	"github.com/nomadcode/nomadcode-core/internal/notification"
)

// TaskNotificationSink adapts the Mattermost client to the
// notification.TaskEventSink fanout interface.  It lives in the
// mattermost adapter package so provider details never cross the
// adapter boundary.
type TaskNotificationSink struct {
	client *Client
}

// NewTaskNotificationSink creates a sink that forwards completed task
// notifications to the given Mattermost client.  The returned sink
// is safe to pass through notification.NewService as a provider-neutral
// TaskEventSink.
//
// A nil client is tolerated (HandleTaskEvent is a no-op).
func NewTaskNotificationSink(client *Client) *TaskNotificationSink {
	return &TaskNotificationSink{client: client}
}

var _ notification.TaskEventSink = (*TaskNotificationSink)(nil)

// HandleTaskEvent implements notification.TaskEventSink.
// Only task.completed events trigger a Mattermost post.
func (s *TaskNotificationSink) HandleTaskEvent(ctx context.Context, event notification.TaskEvent) error {
	if s.client == nil {
		return nil
	}
	if event.Type != notification.TaskEventCompleted {
		return nil
	}
	return s.client.SendTaskNotification(ctx, TaskNotificationInput{
		TaskID:  event.TaskID,
		Title:   strings.TrimSpace(event.Title),
		Status:  strings.TrimSpace(event.Status),
		Message: strings.TrimSpace(event.Message),
	})
}
