# frozen_string_literal: true

require 'arcana'

module Abaci
  class << self
    # Global storage for configuration options.  Sets defaults or pulls ENV variables when appropriate.
    # @return [Hash<Symbol, Object>]
    def config
      @config ||= {
        # AWS defaults
        aws_profile: ENV['AWS_PROFILE'],
        # Arcana defaults
        arcana_bucket: ENV['ARCANA_BUCKET'] || 'arcana-cpe-dev-default-uswest2-5c6bc9b98400aecf95b630cc8ababf31',
        arcana_region: ENV['ARCANA_REGION'] || ENV['AWS_REGION'] || 'us-west-2',
        arcana_system_prefix: ENV['ARCANA_SYSTEM_PREFIX'] || 'litany/pdx',
        # Sensu defaults
        sensu_sns: ENV['SENSU_SNS'] || 'arn:aws:sns:us-west-2:994136867826:sensu_ingress',
        sensu_region: ENV['SENSU_REGION'] || ENV['AWS_REGION'] || 'us-west-2',
        # Service defaults
        service_id: ENV['SERVICE_ID'] || 'abaci-default-cpetools-pdx',
        # Run defaults
        debug: false,
        dry_run: false,
        last: '30m',
        started_at: Time.now.to_i
      }
    end
  end

  # Base mixin that provides helpers to access config and secrets.
  module Base

    # Returns a memoized instance of the arcana client.
    # @return [Arcana::Client]
    def arcana_client
      @arcana_client ||= Arcana::Client.new bucket: config(:arcana_bucket), service_id: config(:service_id), system_prefix: config(:arcana_system_prefix), aws_region: config(:arcana_region), aws_profile: config(:aws_profile)
    end

    # Allows you to retrieve or set a config option
    # @param key [Symbol] The config option you're accessing
    # @param value [Object] The value of the option you're assigning
    # @return [Object] The current or new value of the config option
    def config(key, value = nil)
      value.nil? ? Abaci.config[key] : Abaci.config[key] = value
    end

    # Retrieves a material from Arcana.
    # @param key [String] the name of the material to retrieve from Arcana
    # @return [String] the data stored in Arcana.  Always stored in Arcana as a string, casting to other types is up to the consumer.
    def material(key)
      arcana_client.decrypt(key)
    end
  end
end
