package jump

import (
	"fmt"
	"strings"
)

const (
	gatewayPrefix = "gateway_"
)

// CredentialID is the identifier for a credential in kubeconfig.
type CredentialID string

func FormatCredentialID(dest IDestination) CredentialID {
	return CredentialID(fmt.Sprintf("%s.%s", dest.Type(), dest.ID()))
}

func FormatGatewayCredentialID(dest IDestination) CredentialID {
	return CredentialID(gatewayPrefix + fmt.Sprintf("%s.%s", dest.Type(), dest.ID()))
}

func ParseCredentialID(credID CredentialID) (DestinationType, string) {
	_, typ, id := parseCredentialID(credID)

	return DestinationType(typ), id
}

func IsGatewayCredentialID(credID CredentialID) bool {
	domain, _, _ := parseCredentialID(credID)
	return domain == "gateway"
}

func parseCredentialID(credID CredentialID) (domain string, typ string, id string) {
	if strings.HasPrefix(string(credID), gatewayPrefix) {
		domain = "gateway"
		credID = CredentialID(strings.TrimPrefix(string(credID), gatewayPrefix))
	}

	parts := strings.Split(string(credID), ".")
	if len(parts) == 2 {
		typ = parts[0]
		id = parts[1]
	}

	return
}
