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

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

    position = 1
    agreements_without_position.each do |agreement|
      agreement.update(position: position)
      position += 1
    end

    if agreements_with_position.present?
      agreements_with_position.each do |agreement|
        agreement.update(position: position)
        position += 1
      end
    end
  end

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

    def agreements
      application.application_agreements
    end

    def agreements_without_position
      @agreements_without_position ||= agreements.where(position: nil).to_a
    end

    def agreements_with_position
      @agreements_with_position ||= agreements
        .where.not(id: agreements_without_position)
        .ordered
        .to_a
    end
end
