class Facility::Location < ApplicationRecord
  include Base::Facility::Location

  associations_for legacy: true do |a|
    a.belongs_to :school
  end

  has_many :buildings, class_name: 'Facility::Building', foreign_key: :LocationID,
    dependent: :destroy, inverse_of: :location
  has_many :rooms, through: :buildings
  has_many :classrooms, class_name: 'Classroom', foreign_key: :LocationID, dependent: :nullify,
    inverse_of: :location
  has_many :employees, class_name: 'Employee', foreign_key: :LocationID, dependent: :nullify,
    inverse_of: :location
  has_many :students, class_name: 'Student', foreign_key: :LocationID, dependent: :nullify,
    inverse_of: :location

  has_one :apple_manager_config, foreign_key: :location_id, dependent: :nullify,
    inverse_of: :location

  has_one_attached :photo

  validates :name, presence: true, length: { maximum: 32 }

  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
