require 'rails_helper'

RSpec.describe 'Wiki title collision', type: :request do
  let!(:user) { create_member_user! }

  def auth_headers user
    { 'X-Transfer-Code' => user.inheritance_code }
  end

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

  it 'returns 422 when renaming wiki title to existing title' do
    source = create_wiki_page(title: 'wiki_collision_source', body: 'source body')
    create_wiki_page(title: 'wiki_collision_target', body: 'target body')

    source_revision_count = source.wiki_revisions.count
    source_version_count = source.wiki_versions.count
    old_title = source.title
    old_body = source.body

    put "/wiki/#{ source.id }",
        params: {
          title: 'wiki_collision_target',
          body: 'new body',
          message: 'rename collision',
          base_revision_id: source.current_revision.id,
        },
        headers: auth_headers(user)

    expect(response).to have_http_status(:unprocessable_entity)

    source.reload

    expect(source.title).to eq(old_title)
    expect(source.body).to eq(old_body)
    expect(source.wiki_revisions.count).to eq(source_revision_count)
    expect(source.wiki_versions.count).to eq(source_version_count)
  end

  it 'returns 422 when creating wiki with existing title' do
    create_wiki_page(title: 'wiki_collision_create', body: 'already exists')

    expect {
      post '/wiki',
           params: {
             title: 'wiki_collision_create',
             body: 'new body',
             message: 'duplicate create',
           },
           headers: auth_headers(user)
    }
        .not_to change(WikiPage, :count)

    expect(response).to have_http_status(:unprocessable_entity)
  end
end
