class LogEntry < ActiveRecord::Base

  include ThreeScale::Search::Scopes

  validates :level, :description, :provider, presence: true

  TTL = 6.months

  LEVELS = {
    :info => 10,
    :warning => 20,
    :error => 30
  }

  belongs_to :provider, :class_name => "Account"
  belongs_to :buyer, :class_name => "Account"

  scope :by_buyer_query, ->(query) do
    where("buyer_id IN (?) or buyer_id IS NULL", Account.buyers.search_ids(query))
  end

  self.allowed_search_scopes = [:buyer_query]

  def level
    LEVELS.invert[self[:level]]
  end

  def self.log(type, text, provider, buyer)
    raise 'Cannot log without provider' unless provider

    opts = { :level => LEVELS[type], :description => text, :buyer => buyer }

    if provider.respond_to?(:provider?)
      provider.log_entries.create!(opts)
    else
      LogEntry.create!(opts.merge(:provider_id => provider))
    end
  rescue
    Rails.logger.error("Failed to write log for #{provider}")
  end

  def self.delete_old
    where('created_at < ?', LogEntry::TTL.ago).delete_all
  end


end
