package mongo

import (
	"context"
	"log"
)

func Find[T any](ctx context.Context, settings *RequestSettings) ([]T, error) {
	if settings == nil {
		return []T{}, ErrEmptyArgs
	}

	results := make([]T, 0)

	cursor, err := settings.Driver.Find(ctx, settings.Filter, settings.Options)
	if err != nil {
		return []T{}, err
	}

	defer func() {
		if err := cursor.Close(ctx); err != nil {
			log.Printf("failed to close cursor: %v", err)
		}
	}()

	for cursor.Next(ctx) {
		result := new(T)

		if err := cursor.Decode(result); err != nil {
			return []T{}, err
		}

		results = append(results, *result)
	}

	if err := cursor.Err(); err != nil {
		return []T{}, err
	}

	return results, nil
}

func FindOne[T any](ctx context.Context, settings *RequestSettings) (*T, error) {
	if settings == nil {
		return nil, ErrEmptyArgs
	}

	result := new(T)

	if err := settings.Driver.FindOne(ctx, settings.Filter).Decode(result); err != nil {
		return nil, err
	}

	return result, nil
}
