class Facility::Room < ApplicationRecord
  include Base::Facility::Room

  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 :building, class_name: 'Facility::Building', foreign_key: :BuildingID, optional: true,
    inverse_of: :rooms

  has_many :classrooms, class_name: 'Classroom', foreign_key: :FacilityID, dependent: :nullify,
    inverse_of: :room

  has_many :events, class_name: 'Event', foreign_key: 'FacilityID', dependent: :nullify,
    inverse_of: :room

  associations_for namespace: 'EdFi' do |a|
    a.has_one :id, as: :associated, inverse_of: :associated, dependent: :destroy
  end

  delegate :location, to: :building

  has_one_attached :photo

  scope :by_buildings, ->(ids) { where(building_id: ids) if ids }

  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
