package mongo

import (
	"net"
	"strings"

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

func buildOptions(s *DBSettings) *options.ClientOptions {
	opts := options.Client()

	if s.URI != "" {
		return opts.ApplyURI(s.URI)
	}

	hosts := make([]string, 0, len(s.Hosts)+1)
	for _, h := range s.Hosts {
		if trimmed := strings.TrimSpace(h); trimmed != "" {
			hosts = append(hosts, trimmed)
		}
	}

	if len(hosts) == 0 && s.Host != "" {
		host := s.Host
		if _, _, err := net.SplitHostPort(host); err != nil && s.Port != "" {
			host = net.JoinHostPort(host, s.Port)
		}
		hosts = append(hosts, host)
	}

	if len(hosts) > 0 {
		opts.SetHosts(hosts)
	}

	if s.ReplicaSet != "" {
		opts.SetReplicaSet(s.ReplicaSet)
	}

	cred := options.Credential{
		AuthMechanism: s.AuthMechanism,
		AuthSource:    s.AuthSource,
		Username:      s.User,
		Password:      s.Password,
	}
	opts.SetAuth(cred)

	return opts
}
