class Page < ApplicationRecord
  belongs_to :report, touch: true
  has_many :elements, -> { order(:position) }, dependent: :destroy

  has_rich_text :comment

  before_validation :set_position
  before_update :update_positions, if: :position_changed?

  def full_url
    return nil if report.url.blank? && url.blank?

    [ "https:/", report.url&.sub(/.*:\/\//, ""), url&.sub(/^\//, "") ].compact_blank.join("/")
  end

  private
  def set_position
    self.position ||= (report.pages.pluck(:position).max || 0) + 1
  end

  def update_positions
    if position_was
      report.pages.where("position > ?", position_was).update_all("position = position - 1")
    end
    report.pages.where(position: position..).update_all("position = position + 1")
  end
end
