class Maintenance::Admissions::Attachments::PositionJob
  include Sidekiq::Worker

  def perform(application_id)
    @application_id = application_id
    return if attachments_without_position.empty?

    position = 1
    attachments_without_position.each do |attachment|
      attachment.update(position: position)
      position += 1
    end

    return if attachments_with_position.blank?

    attachments_with_position.each do |attachment|
      attachment.update(position: position)
      position += 1
    end
  end

  private
    def application
      @application ||= Admission::Application.find(@application_id)
    end

    def attachments
      application.application_attachments
    end

    def attachments_without_position
      @attachments_without_position ||= attachments.where(position: nil).to_a
    end

    def attachments_with_position
      @attachments_with_position ||= attachments
        .where.not(id: attachments_without_position)
        .ordered
        .to_a
    end
end
