class User < ApplicationRecord
  devise :database_authenticatable, :recoverable, :registerable, :confirmable,
         :trackable, :rememberable, :validatable, :lockable, :timeoutable

  has_many :client_service_requests,
           class_name: "ServiceRequest",
           foreign_key: :client_id,
           dependent: :restrict_with_error,
           inverse_of: :client

  has_many :agent_service_requests,
           class_name: "ServiceRequest",
           foreign_key: :agent_id,
           dependent: :restrict_with_error,
           inverse_of: :agent

  enum role: {
    client: "client",
    agent: "agent",
    admin: "admin"
  }

  validates :first_name, :last_name, presence: true

  has_one_attached :avatar

  scope :search, lambda { |term|
    where(
      "first_name ILIKE :term OR last_name ILIKE :term OR email ILIKE :term",
      term: "%#{term}%"
    )
  }

  def self.online_agents_count
    agent.where("last_seen_at > ?", 5.minutes.ago).count
  end

  def name
    "#{first_name} #{last_name}"
  end

  def gender_title
    I18n.t("activerecord.attributes.user.genders.#{gender}") if gender.present?
  end
end
