package trending

import (
	"context"
	"encoding/json"
	"tercul/internal/app/analytics"

	"github.com/hibiken/asynq"
)

const (
	TaskUpdateTrending = "task:trending:update"
)

type UpdateTrendingPayload struct {
	// No payload needed for now
}

func NewUpdateTrendingTask() (*asynq.Task, error) {
	payload, err := json.Marshal(UpdateTrendingPayload{})
	if err != nil {
		return nil, err
	}
	return asynq.NewTask(TaskUpdateTrending, payload), nil
}

func HandleUpdateTrendingTask(analyticsService analytics.Service) asynq.HandlerFunc {
	return func(ctx context.Context, t *asynq.Task) error {
		var p UpdateTrendingPayload
		if err := json.Unmarshal(t.Payload(), &p); err != nil {
			return err
		}
		return analyticsService.UpdateTrending(ctx)
	}
}

func RegisterTrendingHandlers(mux *asynq.ServeMux, analyticsService analytics.Service) {
	mux.HandleFunc(TaskUpdateTrending, HandleUpdateTrendingTask(analyticsService))
}
