require 'set'


class WikiPage < ApplicationRecord
  include MyDiscard

  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

  has_many :wiki_versions

  attribute :version_no, :integer, default: 1

  belongs_to :tag_name
  validates :tag_name, presence: true
  validates :body, presence: true

  def title = tag_name.name
  def deprecated_at = tag_name.tag&.deprecated_at

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

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

  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)
  def succ_revision_id(revision_id) =
      wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
end
