import { Timestamp } from '../types'
import { retry } from './retry.ts'
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'

/**
 * Generates a timestamp for the provided nostr event ID.
 * @returns Timestamp with its value and the nostr event ID.
 */
export const generateTimestamp = async (
  nostrId: string
): Promise<Timestamp | undefined> => {
  try {
    return {
      timestamp: await retry(() => timestamp(nostrId)),
      nostrId: nostrId
    }
  } catch (error) {
    console.error(error)
    return
  }
}

const timestamp = async (hash: string): Promise<string> => {
  const detachedTimestamp =
    window.OpenTimestamps.DetachedTimestampFile.fromHash(
      new window.OpenTimestamps.Ops.OpSHA256(),
      hexToBytes(hash)
    )

  await window.OpenTimestamps.stamp(detachedTimestamp)
  const ctx = new window.OpenTimestamps.Context.StreamSerialization()
  detachedTimestamp.serialize(ctx)
  const timestampBytes = ctx.getOutput()
  const hex = bytesToHex(timestampBytes)

  return hex
}
