defmodule CounterExample.Create do
  @moduledoc """
  Logic to create counter resources.
  """

  alias Anoma.Arm.NullifierKey
  alias Anoma.Arm.NullifierKeyCommitment
  alias Anoma.Arm.Resource
  alias Anoma.Util
  alias CounterExample.NIF

  @doc """
  Create a new ephemeral counter.

  A counter is represented by its owner, and a unique label.
  """
  @spec create_ephemeral_counter(NullifierKeyCommitment.t()) :: Resource.t()
  def create_ephemeral_counter(commitment) do
    # Create a counter resource
    %Resource{
      logic_ref: NIF.counter_logic_ref(),
      label_ref: :crypto.strong_rand_bytes(32),
      quantity: 1,
      value_ref: Util.pad_bitstring(<<0>>, 32),
      is_ephemeral: true,
      nonce: :crypto.strong_rand_bytes(32),
      nk_commitment: commitment
    }
  end

  @doc """
  Given an ephemeral counter, creates a new counter to be created.

  The ephemeral counter serves as the resource we are consuming, in order to
  creeate the new counter.
  """
  @spec create_new_counter(NullifierKeyCommitment.t(), Resource.t(), NullifierKey.t()) ::
          Resource.t()
  def create_new_counter(commitment, ephemeral_counter, ephemeral_counter_nf_key) do
    %{
      ephemeral_counter
      | is_ephemeral: false,
        rand_seed: :crypto.strong_rand_bytes(32),
        nonce: Resource.nullifier(ephemeral_counter, ephemeral_counter_nf_key),
        value_ref: <<1, 0::31*8>>,
        nk_commitment: commitment
    }
  end
end
