/**
 * JWT token signing and verification example
 *
 * This example demonstrates how to sign and verify JWT tokens for moq-relay authentication.
 * Run with: bun run examples/sign-and-verify.ts
 */
import { authorize, type Claims, load, sign, verify } from "../src/index.ts";

async function main() {
	// Load a JWK key generated by rs/moq-token
	const jwkString = `{
  "alg": "HS256",
  "key_ops": ["sign", "verify"],
  "k": "your-base64url-encoded-secret-that-is-at-least-32-bytes-long",
  "kid": "my-key-id",
  "kty": "oct"
}`;
	const key = load(jwkString);

	// Create claims
	const claims: Claims = {
		root: "demo",
		put: "bbb", // Only `demo/bbb`
		get: "", // Any broadcast starting with `demo/`
		exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now (in seconds)
		iat: Math.floor(Date.now() / 1000), // Issued at (in seconds)
	};

	// Sign a token
	const token = await sign(key, claims);
	console.log("Token:", token);

	// Verify a token (symmetric keys). This checks the signature and expiry only.
	const verifiedClaims = await verify(key, token);
	console.log("Verified claims:", verifiedClaims);

	// Scope the claims to a connection path, the way a relay does. Connecting to
	// demo/bbb consumes the "bbb" grant, leaving publish access to the path itself.
	const permissions = authorize(verifiedClaims, "demo/bbb");
	console.log("Permissions at demo/bbb:", permissions);
}

main().catch(console.error);
