export interface MutationRequestContext {
  idempotencyKey: string
  correlationId: string
  traceparent: string
  headers: Headers
}

function randomHex(length: number): string {
  const bytes = crypto.getRandomValues(new Uint8Array(Math.ceil(length / 2)))
  return Array.from(bytes, value => value.toString(16).padStart(2, '0'))
    .join('')
    .slice(0, length)
}

export function createMutationRequestContext(
  operation: string,
  stableKey?: string,
): MutationRequestContext {
  const correlationId = crypto.randomUUID()
  const idempotencyKey = stableKey?.trim()
    ? `${operation}:${stableKey.trim()}`
    : `${operation}:${crypto.randomUUID()}`
  const traceparent = `00-${randomHex(32)}-${randomHex(16)}-01`
  const headers = new Headers({
    'Idempotency-Key': idempotencyKey,
    'X-Correlation-ID': correlationId,
    traceparent,
  })

  return {
    idempotencyKey,
    correlationId,
    traceparent,
    headers,
  }
}
