package opaquekey

import (
	"encoding/base64"
	"errors"
	"strings"
)

const keyDelim = ":"

// Errors
var (
	ErrInvalidEncodedKey = errors.New("invalid encoded key")
)

// MarshalBase64Key converts list of composite keys into a base64-encoded key
func MarshalBase64Key(keys ...string) string {
	bs := []byte(strings.Join(keys, keyDelim))
	return base64.RawURLEncoding.EncodeToString(bs)
}

// UnmarshalBase64Key converts a base64-encoded key to a list of composite keys
func UnmarshalBase64Key(key string, length int) ([]string, error) {
	raw, err := base64.RawURLEncoding.DecodeString(string(key))
	if err != nil {
		return nil, err
	}

	keys := strings.SplitN(string(raw), keyDelim, length)
	if len(keys) != length {
		return nil, ErrInvalidEncodedKey
	}
	return keys, nil
}
