package seed

import (
	"crypto/sha256"
	"encoding/hex"
	"testing"
)

// TestHashTokenMatchesSHA256Hex pins HashToken to the exact transformation the
// backend session resolver uses (hex-encoded SHA-256), the invariant that makes a
// seeded session resolve.
func TestHashTokenMatchesSHA256Hex(t *testing.T) {
	const token = "an-example-bearer-token"
	sum := sha256.Sum256([]byte(token))
	want := hex.EncodeToString(sum[:])
	if got := HashToken(token); got != want {
		t.Fatalf("HashToken(%q) = %s, want %s", token, got, want)
	}
}

// TestGenerateTokenRoundTrip checks that a minted token hashes to the stored hash and
// that tokens are unique.
func TestGenerateTokenRoundTrip(t *testing.T) {
	token, hash, err := GenerateToken()
	if err != nil {
		t.Fatalf("GenerateToken: %v", err)
	}
	if token == "" || hash == "" {
		t.Fatal("empty token or hash")
	}
	if len(hash) != 64 {
		t.Fatalf("hash length = %d, want 64 hex chars", len(hash))
	}
	if got := HashToken(token); got != hash {
		t.Fatalf("hash mismatch: GenerateToken returned %s, HashToken(token) = %s", hash, got)
	}
	token2, _, err := GenerateToken()
	if err != nil {
		t.Fatalf("GenerateToken (2nd): %v", err)
	}
	if token2 == token {
		t.Fatal("two generated tokens are identical")
	}
}
