package mutil

import (
	"context"

	"github.com/tech/sendico/pkg/db/repository"
	"github.com/tech/sendico/pkg/db/repository/builder"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

func GetObjects[T any](ctx context.Context, logger mlogger.Logger, filter builder.Query, cursor *model.ViewCursor, repo repository.Repository) ([]T, error) {
	entities := make([]T, 0)
	decoder := func(cur *mongo.Cursor) error {
		var next T
		if e := cur.Decode(&next); e != nil {
			logger.Warn("Failed to decode entity", zap.Error(e))
			return e
		}
		entities = append(entities, next)
		return nil
	}
	return entities, repo.FindManyByFilter(ctx, repository.ApplyCursor(filter, cursor), decoder)
}
