package mongo

import (
	"context"
	"fmt"
	"net/url"

	"git.k-space.ee/k-space/logmower-shipper/pkg/globals"
	"go.mongodb.org/mongo-driver/mongo"
)

func Initialize(ctx context.Context, uri string) (*mongo.Collection, error) {
	uriParsed, err := url.ParseRequestURI(uri)
	if err != nil {
		return nil, fmt.Errorf("parsing URI for database name: %w", err)
	}

	uriParsed.Path = uriParsed.Path[1:] // remove leading slash
	if uriParsed.Path == "" {
		return nil, fmt.Errorf("URI must include database name (as database to authenticate against)")
	}

	dbOpt := monitoredClientOptions().ApplyURI(uri)

	dbClient, err := mongo.Connect(globals.MongoTimeout(ctx), dbOpt)
	if err != nil {
		return nil, fmt.Errorf("connecting to %q: %w", dbOpt.GetURI(), err)
	}

	if err := dbClient.Ping(globals.MongoTimeout(ctx), nil); err != nil {
		return nil, fmt.Errorf("first ping to database: %w", err)
	}

	col := dbClient.Database(uriParsed.Path).Collection("logs")

	if err := InitializeIndexes(globals.MongoTimeout(ctx), col); err != nil {
		return nil, fmt.Errorf("initializing indexes: %w", err)
	}

	return col, nil
}
