package mo

import (
	"context"
	"time"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)

const (
	DefaultTimout = 10 * time.Second
)

func Dial(address string) (*Client, error) {
	return DialOptions(options.Client().ApplyURI(address))
}

func DialOptions(opts *options.ClientOptions) (*Client, error) {
	if opts.Timeout == nil {
		opts.SetConnectTimeout(DefaultTimout)
	}
	if opts.ConnectTimeout == nil {
		opts.SetConnectTimeout(DefaultTimout / 2)
	}
	if opts.AppName == nil {
		opts.SetAppName("git.simanc.com/software/golib/v4")
	}
	return mongo.Connect(opts)
}

func Ping(c *Client) error {
	ctx, cancel := context.WithTimeout(context.Background(), DefaultTimout)
	defer cancel()
	_ = c.Ping(ctx, readpref.Primary())
	return nil
}
