package provision

import (
	"fmt"
	"regexp"
	"strings"

	"sub2api-cn-relay-manager/internal/pack"
)

var nonSlugPattern = regexp.MustCompile(`[^a-z0-9]+`)

type ResourceNames struct {
	Group   string
	Channel string
	Plan    string
}

func SuggestAccountNamePrefix(provider pack.ProviderManifest) string {
	return fmt.Sprintf("%s-", resourceSlug(provider.ProviderID))
}

func SuggestResourceNames(provider pack.ProviderManifest) ResourceNames {
	slug := resourceSlug(provider.ProviderID)
	return ResourceNames{
		Group:   fallbackString(strings.TrimSpace(provider.GroupTemplate.Name), fmt.Sprintf("crm-%s-group", slug)),
		Channel: fallbackString(strings.TrimSpace(provider.ChannelTemplate.Name), fmt.Sprintf("crm-%s-channel", slug)),
		Plan:    fallbackString(strings.TrimSpace(provider.PlanTemplate.Name), fmt.Sprintf("crm-%s-plan", slug)),
	}
}

func resourceSlug(raw string) string {
	slug := strings.ToLower(strings.TrimSpace(raw))
	slug = nonSlugPattern.ReplaceAllString(slug, "-")
	slug = strings.Trim(slug, "-")
	if slug == "" {
		return "provider"
	}
	return slug
}

func fallbackString(values ...string) string {
	for _, value := range values {
		if trimmed := strings.TrimSpace(value); trimmed != "" {
			return trimmed
		}
	}
	return ""
}
