# frozen_string_literal: true

module EnvHelper
  class RequiredEnvError < StandardError; end

  module_function

  def load(key, default = nil, message: '', raise: false)
    env_key = key.to_s.upcase.strip
    default_message(key, default)
    ENV[env_key] ||= default

    return ENV[env_key] if ENV[env_key].present?

    raise RequiredEnvError, missing_message(key, message) if raise

    puts missing_message(key, message)
    nil
  end

  def missing_message(key, message = '')
    msg = "🚫 ENV NOT SET: #{key}"
    msg += "\s-\s#{message}" if message.present?
    msg
  end

  def default_message(key, default = nil)
    return if ENV[key].present? && default.blank?

    puts "✅ ENV #{key} DEFAULT: #{output_default(key, default)}"
  end

  def output_default(key, default)
    return '🤐 SECRET REDACTED' if key.include?('SECRET') || key.ends_with?('API_KEY')

    default
  end
end
