require 'rails_helper'

RSpec.describe WikiVersionRecorder do
  let(:user) { create_member_user! }

  def create_page title:, body: 'body'
    Wiki::Commit.create_content!(
        tag_name: TagName.create!(name: title),
        body:,
        created_by_user: user,
        message: 'init')
  end

  describe '.record!' do
    it 'records title, body, reason, user, and version number' do
      page = create_page(title: 'wiki_version_recorder_basic', body: 'body')

      expect {
        described_class.record!(
            page:,
            event_type: :update,
            reason: 'manual reason',
            created_by_user: user)
      }
          .to change { page.reload.wiki_versions.count }.by(1)

      version = page.wiki_versions.order(:version_no).last

      expect(version).to have_attributes(
        version_no: 2,
        event_type: 'update',
        title: 'wiki_version_recorder_basic',
        body: 'body',
        reason: 'manual reason',
        created_by_user_id: user.id
      )
    end

    it 'does not create duplicated update version for identical snapshot' do
      page = create_page(title: 'wiki_version_recorder_duplicate', body: 'body')

      described_class.record!(
          page:,
          event_type: :update,
          reason: nil,
          created_by_user: user)

      before_count = page.reload.wiki_versions.count

      described_class.record!(
          page:,
          event_type: :update,
          reason: nil,
          created_by_user: user)

      expect(page.reload.wiki_versions.count).to eq(before_count)
    end

    it 'creates update version when title changes' do
      page = create_page(title: 'wiki_version_recorder_title_before', body: 'body')
      page.tag_name.update!(name: 'wiki_version_recorder_title_after')

      expect {
        described_class.record!(
            page:,
            event_type: :update,
            reason: 'rename',
            created_by_user: user)
      }
          .to change { page.reload.wiki_versions.count }.by(1)

      version = page.wiki_versions.order(:version_no).last

      expect(version.title).to eq('wiki_version_recorder_title_after')
      expect(version.body).to eq('body')
      expect(version.reason).to eq('rename')
    end

    it 'creates update version when body changes' do
      page = create_page(title: 'wiki_version_recorder_body', body: 'before')
      page.update!(body: 'after')

      expect {
        described_class.record!(
            page:,
            event_type: :update,
            reason: 'body',
            created_by_user: user)
      }
          .to change { page.reload.wiki_versions.count }.by(1)

      version = page.wiki_versions.order(:version_no).last

      expect(version.title).to eq('wiki_version_recorder_body')
      expect(version.body).to eq('after')
      expect(version.reason).to eq('body')
    end
  end
end
