package mill

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
)

// bootstrapTokenName is the identity the mill seeds cfg.SharedSecret under so a
// single-secret dev fleet works without minting. Production registers per-executor
// identities with `spindle mill executor add`.
const bootstrapTokenName = "dev-bootstrap"

func GenerateToken() (string, error) {
	var b [32]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(b[:]), nil
}

// HashToken hashes a raw token for storage/lookup. The mill only ever persists
// and compares hashes, so a DB leak never exposes a usable token, and lookup by
// hash avoids a secret-dependent comparison.
func HashToken(token string) string {
	sum := sha256.Sum256([]byte(token))
	return hex.EncodeToString(sum[:])
}
