class Agent < ApplicationRecord
  validates :phone_number, presence: true
  validates :name, presence: true
  has_many :licenses
  has_and_belongs_to_many :carriers

  scope :match, lambda { |industry_id, state|
    joins("INNER JOIN licenses ON licenses.agent_id = agents.id")
    .joins("INNER JOIN agents_carriers ON agents_carriers.agent_id = agents.id")
    .joins("INNER JOIN carriers ON carriers.id = agents_carriers.carrier_id")
    .joins("INNER JOIN carriers_industries ON carriers_industries.carrier_id = carriers.id")
    .joins("INNER JOIN industries ON industries.id = carriers_industries.industry_id")
    .where("industries.id = ? AND licenses.state = ?", industry_id, state)
    .distinct
  }

  def self.search(phone_number)
    return nil unless phone_number.present?
    Agent.find { |a| a.phone_number.try(:digits_only) == phone_number.digits_only }
  end
end
