// Package seed creates accounts, identities and sessions directly in the backend
// Postgres schema so the load driver can authenticate as many pre-provisioned
// players without paying the per-IP cost of the auth edge operations. It owns the
// inverse operation too (cleanup of everything it created).
package seed

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

// GenerateToken mints an opaque bearer token and its stored hash. token is the
// plaintext handed to the client; hash is what the seeder writes to
// sessions.token_hash. The transformation matches backend/internal/session so a
// resolve of token recomputes the same hash and finds the seeded row.
func GenerateToken() (token, hash string, err error) {
	buf := make([]byte, 32)
	if _, err := rand.Read(buf); err != nil {
		return "", "", err
	}
	token = base64.RawURLEncoding.EncodeToString(buf)
	return token, HashToken(token), nil
}

// HashToken returns the hex-encoded SHA-256 of token. It is the exact hash the
// backend session resolver computes (backend/internal/session/token.go), kept in
// lockstep so seeded sessions validate.
func HashToken(token string) string {
	sum := sha256.Sum256([]byte(token))
	return hex.EncodeToString(sum[:])
}
