/**
 * Cryptographic utilities for A2A delegation chain signing and verification.
 * Uses HMAC-SHA256 to produce and verify delegation payload signatures.
 */

import { createHmac, randomUUID } from 'crypto';
import { DelegationTokenPayload } from '../types/delegation.js';

/**
 * Signs a delegation payload using HMAC-SHA256.
 *
 * @param payload - The delegation token payload to sign.
 * @param secret - The HMAC signing secret.
 * @returns Hex-encoded HMAC-SHA256 digest of the serialised payload.
 */
export function signDelegationPayload(payload: DelegationTokenPayload, secret: string): string {
  const data = JSON.stringify(payload);
  return createHmac('sha256', secret).update(data).digest('hex');
}

/**
 * Verifies a delegation payload against an expected HMAC-SHA256 signature.
 *
 * @param payload - The delegation token payload to verify.
 * @param signature - The hex-encoded signature to check against.
 * @param secret - The HMAC signing secret.
 * @returns `true` if the signature is valid, `false` otherwise.
 */
export function verifyDelegationSignature(
  payload: DelegationTokenPayload,
  signature: string,
  secret: string,
): boolean {
  const expected = signDelegationPayload(payload, secret);
  return expected === signature;
}

/**
 * Generates a unique delegation token (UUID v4).
 *
 * @returns A random UUID string to use as the delegation token.
 */
export function generateDelegationToken(): string {
  return randomUUID();
}
