package regionalexecutor

import (
	"fmt"
	"net/url"
	"path"
	"strings"
)

const BasePath = "/metrics-integration-regional"

func BuildURL(executorURL, endpointPath string) (string, error) {
	trimmed := strings.TrimSpace(executorURL)
	if trimmed == "" {
		return "", fmt.Errorf("executor URL is empty")
	}

	parsed, err := url.Parse(trimmed)
	if err != nil {
		return "", fmt.Errorf("invalid executor URL %q: %w", executorURL, err)
	}
	if parsed.Scheme != "http" && parsed.Scheme != "https" {
		return "", fmt.Errorf("invalid executor URL %q: scheme must be http or https", executorURL)
	}
	if parsed.Host == "" {
		return "", fmt.Errorf("invalid executor URL %q: host is empty", executorURL)
	}

	basePath := strings.TrimRight(parsed.Path, "/")
	if !strings.HasSuffix(basePath, BasePath) {
		basePath = path.Join(basePath, BasePath)
	}

	parsed.Path = path.Join(basePath, endpointPath)
	parsed.RawPath = parsed.EscapedPath()

	return parsed.String(), nil
}
