package auth

import (
	"github.com/google/uuid"
	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/utils"
	"strings"
)

// GenerateNewApiKey generates a 32 character API key. If the build environment is dev or stage the key will start with
// "dev_" or "stage_" respectively.
func GenerateNewApiKey() string {
	uniqueKey := uuid.New().String()
	uniqueKey = strings.ReplaceAll(uniqueKey, "-", "")

	env := utils.GetEnv("ENVIRONMENT", "")
	if env == "dev" || env == "stage" {
		uniqueKey = env + "_" + uniqueKey
	}

	return uniqueKey
}

// GetApiKeyFromHeaders checks if a bearer token is passed as part of the Authorization header and returns that key.
// NOTE: This function is deprecated. It simply calls the more generic GetBearerTokenFromHeaders.
func GetApiKeyFromHeaders(headers map[string]string) string {
	return GetBearerTokenFromHeaders(headers)
}

// MaskAPIKey masks an API key in the form "abc***xyz"
func MaskAPIKey(key string) string {
	keyRunes := []rune(key)
	keyLength := len(keyRunes)
	if keyLength > 6 {
		return string(keyRunes[:3]) + "***" + string(keyRunes[keyLength-3:])
	}
	// This shouldn't happen, but if we don't have more than 6 characters, mask in the form "***z"
	return "***" + string(keyRunes[keyLength-1])
}