require 'yaml'

module Nadir
  class Config
    attr_accessor :api_key,
                  :api_url,
                  :env,
                  :logger,
                  :root,
                  :enabled_for

    def initialize
      @env         = ENV['NADIR_ENV'] || ENV['RAILS_ENV'] || ENV['RACK_ENV']
      @api_key     = ENV['NADIR_API_KEY']
      @api_url     = 'https://nadir.dev/api'.freeze
      @enabled_for = %w(production staging)

      @logger      = Logger.new(STDOUT)
    end

    def validate
      unless @api_key
        logger.warn '[Nadir] API-KEY not set, skipping notifications.'

        return false
      end

      unless @enabled_for.include? @env.to_s
        logger.warn "[Nadir] Reporting disabled for environment '#{@env}', skipping notification."

        return false
      end

      true
    end

    def load_for(app)
      @env  ||= Rails.env
      @root   = app.root

      config_file = @root.join 'config/nadir.yml'

      file_config = YAML.safe_load File.read config_file

      @api_key     = file_config['api_key'] if file_config['api_key']
      @api_url     = file_config['api_url'] if file_config['api_url']
      @enabled_for = file_config['enabled_for'] if file_config['enabled_for']
    end
  end
end