module PageflowScrolled
  class Chapter < Pageflow::ApplicationRecord # rubocop:todo Style/Documentation
    POSITION_ORDER = [
      'pageflow_scrolled_storylines.position ASC',
      'pageflow_scrolled_chapters.position ASC'
    ].join(',')

    include Pageflow::SerializedConfiguration
    include Pageflow::AutoGeneratedPermaId
    include Pageflow::NestedRevisionComponent

    belongs_to :storyline, touch: true
    has_many :sections,
             -> { order('pageflow_scrolled_sections.position ASC') },
             dependent: :destroy,
             inverse_of: :chapter
    has_many :content_elements, through: :sections

    nested_revision_components :sections

    def entry_for_auto_generated_perma_id
      storyline.revision.entry
    end

    def create_section(attributes = {})
      shift_section_positions(from: attributes[:position])

      section = sections.create!(attributes)
      section.content_elements.create!(type_name: 'textBlock')

      section
    end

    def duplicate_section(section)
      transaction do
        shift_section_positions(from: section.position + 1)

        section.duplicate do |new_section|
          new_section.position = section.position + 1
        end
      end
    end

    def self.all_for_revision(revision)
      joins(storyline: :revision)
        .where(pageflow_scrolled_storylines: {revision_id: revision})
        .order(POSITION_ORDER)
    end

    private

    def shift_section_positions(from:)
      sections
        .where('position >= ?', from)
        .update_all('position = position + 1')
    end
  end
end
