package batch

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net/url"
	"path"
	"strings"
)

func NormalizeProviderID(baseURL string) string {
	parsedURL, err := url.Parse(strings.TrimSpace(baseURL))
	if err != nil {
		return ""
	}
	if parsedURL.Scheme == "" || parsedURL.Host == "" {
		return ""
	}

	normalizedHost := normalizeProviderHost(parsedURL.Hostname())
	normalizedPath := path.Clean(strings.TrimSpace(parsedURL.EscapedPath()))
	if normalizedPath == "." {
		normalizedPath = ""
	}

	normalizedURL := parsedURL.Scheme + "://" + strings.ToLower(parsedURL.Hostname()) + normalizedPath
	digest := sha256.Sum256([]byte(normalizedURL))
	hash := hex.EncodeToString(digest[:])
	if len(hash) > 8 {
		hash = hash[len(hash)-8:]
	}

	if normalizedHost == "" {
		normalizedHost = "provider"
	}
	return fmt.Sprintf("%s-%s", normalizedHost, hash)
}

func normalizeProviderHost(host string) string {
	host = strings.TrimSpace(strings.ToLower(host))
	if host == "" {
		return ""
	}

	parts := strings.Split(host, ".")
	filtered := make([]string, 0, len(parts))
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		filtered = append(filtered, part)
	}

	if len(filtered) > 1 {
		filtered = filtered[:len(filtered)-1]
	}
	if len(filtered) == 0 {
		return strings.ReplaceAll(host, ".", "-")
	}
	return strings.Join(filtered, "-")
}
