package wmo

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func (c *Coll[TData]) FindOne(ctx context.Context, filter bson.M) (TData, error) {
	mongoRes := c.coll.FindOne(ctx, filter)

	return c.decodeSingle(ctx, mongoRes)
}

func (c *Coll[TData]) FindOneOpt(ctx context.Context, filter bson.M) (*TData, error) {
	mongoRes := c.coll.FindOne(ctx, filter)

	res, err := c.decodeSingle(ctx, mongoRes)
	if err == mongo.ErrNoDocuments {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	return &res, nil
}

func (c *Coll[TData]) FindOneByID(ctx context.Context, id EntityID) (TData, error) {
	mongoRes := c.coll.FindOne(ctx, bson.M{"_id": id})

	return c.decodeSingle(ctx, mongoRes)
}

func (c *Coll[TData]) FindOneOptByID(ctx context.Context, id EntityID) (*TData, error) {
	mongoRes := c.coll.FindOne(ctx, bson.M{"_id": id})

	res, err := c.decodeSingle(ctx, mongoRes)
	if err == mongo.ErrNoDocuments {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	return &res, nil
}

func (c *Coll[TData]) Find(ctx context.Context, filter bson.M, opts ...*options.FindOptions) ([]TData, error) {
	cursor, err := c.coll.Find(ctx, filter, opts...)
	if err != nil {
		return nil, err
	}

	res, err := c.decodeAll(ctx, cursor)
	if err != nil {
		return nil, err
	}

	return res, nil
}