package main

import (
	"crypto/rand"
	"encoding/base32"

	restful "github.com/emicklei/go-restful"
)

var clusterTokens = newClusterSecretKV[string]("tokens")

func getOrCreateClusterToken(cluster, name string) (token string, err error) {
	key := cluster + "/" + name

	token, found, err := clusterTokens.Get(key)

	if err != nil || found {
		return
	}

	b := make([]byte, 16)
	_, err = rand.Read(b)
	if err != nil {
		return
	}

	token = base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b)

	err = clusterTokens.Put(key, token)
	return
}

func wsClusterTokens(req *restful.Request, resp *restful.Response) {
	clusterName := req.PathParameter("cluster-name")
	clusterTokens.WsList(resp, clusterName+"/")
}

func wsClusterToken(req *restful.Request, resp *restful.Response) {
	clusterName := req.PathParameter("cluster-name")
	name := req.PathParameter("token-name")

	clusterTokens.WsGet(resp, clusterName+"/"+name)
}
