require 'dotenv/environment'

module ERDL
  class Secrets
    def self.load
      return Dotenv.load if ENV['ERDL_DOTENV'].nil?
      expanded = File.expand_path(ENV['ERDL_DOTENV'])
      fail ".env file does not exist at path: #{expanded}" unless File.exist?(expanded)
      Dotenv.load(expanded)
    end

    # Public: Ensure that all the secrets from .env.example are loaded in ENV.
    #
    # Examples
    #
    #   Given a .env.example with the simple contents of "KEY=VALUE", and no .env
    #
    #   SecretsValidator.ensure_all_present
    #   # => KEY was not set in .env! (RuntimeError)
    #
    # Raises a RuntimeError if any of the keys in .env.example have not been loaded in ENV.
    #
    # Returns nothing.
    def self.ensure_all_present(baseline_dotenv = nil)
      baseline_dotenv ||= File.expand_path('../../../.env.example', __FILE__)
      # Should be a Hash: https://github.com/bkeepers/dotenv/blob/master/lib/dotenv/environment.rb
      example = Dotenv::Environment.new(baseline_dotenv)
      example.each do |k, _v|
        fail "#{k} was not set in .env!" if ENV[k].nil?
      end
    end
  end
end
