package loadbalancer

import (
	"errors"
	"net/url"
	"slices"
	"strings"
)

func parseURL(serverURL, newHost string) (string, string, error) {
	parsedURL, err := url.Parse(serverURL)
	if err != nil {
		return "", "", err
	}
	if parsedURL.Host == "" {
		return "", "", errors.New("Initial server URL host is not defined for load balancer")
	}
	address := parsedURL.Host
	if parsedURL.Port() == "" {
		if strings.ToLower(parsedURL.Scheme) == "http" {
			address += ":80"
		}
		if strings.ToLower(parsedURL.Scheme) == "https" {
			address += ":443"
		}
	}
	parsedURL.Host = newHost
	return address, parsedURL.String(), nil
}

// sortServers returns a sorted, unique list of strings, with any
// empty values removed. The returned bool is true if the list
// contains the search string.
func sortServers(input []string, search string) ([]string, bool) {
	result := []string{}
	found := false
	skip := map[string]bool{"": true}

	for _, entry := range input {
		if skip[entry] {
			continue
		}
		if search == entry {
			found = true
		}
		skip[entry] = true
		result = append(result, entry)
	}

	slices.Sort(result)
	return result, found
}
