# frozen_string_literal: true

module Litany

  # A lazily evaluated representation of a string secret
  class ArcanaSecret < String
    class << self

      # Factory to construct new instances
      # @param project [Project] the project scope this secret belongs to
      # @param material [String] name of the secret this represents
      # @return [ArcanaSecret]
      def for(project, material)
        secret = ArcanaSecret.new
        secret.configure(project, material)
        secret
      end
    end

    # Configures the specifics about this secret
    # @param project [Project] the project scope this secret belongs to
    # @param material [String] name of the secret this represents
    # @return [void]
    def configure(project, material)
      @project = project
      @material = material
    end

    def inspect
      "<ArcanaSecret: Material: #{@material}; Project: #{@project.name}; Environment: #{@project.active_environment&.name || :unset}>"
    end

    def to_json(*args)
      to_s.to_json(*args)
    end

    # Resolves the secret from Arcana and memorizes it's value.
    # @return [String]
    def resolve
      raise "Attempting to decrypt Arcana material `#{@material}`, but Arcana support is not enabled." unless ArcanaSupport.enabled?

      @resolve ||= @project.arcana_client.decrypt_and_strip(@material)
    end

    def to_s
      inspect
    end
  end
end

