# require 'pry'

class Log < ApplicationRecord
  belongs_to :user
  belongs_to :package
  belongs_to :screenshot
  validates :message, presence: true

  validates :section, presence: true
  #validates :section, inclusion: { in: ['importer', 'upload', 'frontend'] }

  validates :level, presence: true
  #validates :level, inclusion: { in: ['info', 'error'] }

  default_scope {
    order('id DESC')
  }

  def self.log(message, ip: nil, user: nil, section: 'frontend', level: 'info', screenshot: nil, package: nil)
    log = Log.new

    ip_address = request.remote_ip if defined? request
    token = session[:token] if defined? session

    log.message = message
    log.section = section
    log.level = level
    log.ip_address = ip.to_s
    log.screenshot = screenshot
    log.package = package
    log.user = user # current_user
    logger.error "Could not log to database - validation errors: #{log.errors.to_a}" unless log.valid?
    log.save
    # log
    logger.info "Log.log - #{log.section} - #{log.message}"
  end
end
