package mongo

import (
	"context"
	"time"

	mongodriver "go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"scheduler-backend/pkg/config"
)

type Databases struct {
	Client     *mongodriver.Client
	MetaDB     *mongodriver.Database
	BusinessDB *mongodriver.Database
}

func Connect(ctx context.Context, cfg config.Config) (*Databases, error) {
	client, err := mongodriver.Connect(ctx, options.Client().ApplyURI(cfg.MongoURI()))
	if err != nil {
		return nil, err
	}

	pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	if err := client.Ping(pingCtx, nil); err != nil {
		return nil, err
	}

	return &Databases{
		Client:     client,
		MetaDB:     client.Database(cfg.SchedulerMongoDatabase),
		BusinessDB: client.Database(cfg.BusinessMongoDatabase),
	}, nil
}
