require 'set'


class WikiPage < ApplicationRecord
  has_many :wiki_revisions, dependent: :destroy
  belongs_to :created_user, class_name: 'User'
  belongs_to :updated_user, class_name: 'User'

  has_many :redirected_from_revisions,
           class_name: 'WikiRevision',
           foreign_key: :redirect_page_id,
           dependent: :nullify

  belongs_to :tag_name
  validates :tag_name, presence: true

  def title
    tag_name.name
  end

  def title= val
    (self.tag_name ||= build_tag_name).name = val
  end

  def current_revision
    wiki_revisions.order(id: :desc).first
  end

  def body
    rev = current_revision
    rev.body if rev&.content?
  end

  def resolve_redirect limit: 10
    page = self
    visited = Set.new

    limit.times do
      return page if visited.include?(page.id)

      visited.add(page.id)

      rev = page.current_revision
      return page if !(rev&.redirect?) || !(rev.redirect_page)

      page = rev.redirect_page
    end

    page
  end

  def pred_revision_id revision_id
    wiki_revisions.where('id < ?', revision_id).order(id: :desc).limit(1).pick(:id)
  end

  def succ_revision_id revision_id
    wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
  end
end
