class Facility::Building < ApplicationRecord
  include Base::Facility::Building

  associations_for legacy: true do |a|
    a.belongs_to :school
    a.belongs_to :owner, class_name: 'User', primary_key: :UserID, optional: true
  end

  belongs_to :location, class_name: 'Facility::Location', foreign_key: :LocationID, optional: true,
    inverse_of: :buildings

  has_many :rooms, -> { order(:name) }, class_name: 'Facility::Room', foreign_key: :BuildingID,
    dependent: :destroy, inverse_of: :building
  has_many :employees, class_name: 'Employee', foreign_key: :BuildingID, dependent: :nullify,
    inverse_of: :building

  has_one_attached :photo

  scope :by_locations, ->(ids) { where(location_id: ids) if ids }
  scope :ordered, -> { order(:name) }

  def file_path
    school.dir_path.join('Facilities', picture)
  end

  def migrate_photo
    return if photo.attached? || !picture?

    photo.attach(io: File.open(file_path), filename: picture)
  end
end
