package taskevents

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

	"cloud.google.com/go/pubsub"

	pkgconfig "github.com/tidbcloud/infra-provider/pkg/config"
)

// TaskEvent describe the status of the event, we can make it more detailed, such as preparing, running, done.
type TaskEvent struct {
	Resource    string    `json:"resource"`
	Namespace   string    `json:"namespace"`
	Name        string    `json:"name"`
	Task        string    `json:"task"`
	Status      string    `json:"status"`
	ResourceAge float64   `json:"resource_age"`
	EventTime   time.Time `json:"time"`
}

func PublishTaskEvent(ctx context.Context, topicCli *pubsub.Topic, taskevent TaskEvent) {
	body, err := json.Marshal(taskevent)
	if err != nil {
		return
	}

	topicCli.Publish(ctx, &pubsub.Message{
		Data: body,
	})
}

func IsEnabled(config pkgconfig.RootConfig) bool {
	return config.TaskEvents.TopicID != ""
}
