# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'getting merge request listings (EE) nested in a project' do
  include GraphqlHelpers

  let_it_be(:project) { create(:project, :repository, :public) }
  let_it_be(:current_user) { create(:user) }

  let_it_be(:merge_request_a) { create(:merge_request, :unique_branches, source_project: project) }
  let_it_be(:merge_request_b) { create(:merge_request, :closed, :unique_branches, source_project: project) }
  let_it_be(:merge_request_c) { create(:merge_request, :closed, :unique_branches, source_project: project) }

  let(:results) { graphql_data.dig('project', 'mergeRequests', 'nodes') }

  let(:query) do
    query_merge_requests(all_graphql_fields_for('MergeRequest', max_depth: 1))
  end

  def query_merge_requests(fields)
    graphql_query_for(
      :project,
      { full_path: project.full_path },
      query_graphql_field(:merge_requests, search_params, [
        query_graphql_field(:nodes, nil, fields)
      ])
    )
  end

  def execute_query
    query = query_merge_requests(requested_fields)
    post_graphql(query, current_user: current_user)
  end

  context 'when requesting `approved_by`' do
    let(:search_params) { { iids: [merge_request_a.iid.to_s, merge_request_b.iid.to_s] } }
    let(:extra_iid_for_second_query) { merge_request_c.iid.to_s }
    let(:requested_fields) { query_graphql_field(:approved_by, nil, query_graphql_field(:nodes, nil, [:username])) }

    it 'exposes approver username' do
      merge_request_a.approver_users << current_user

      execute_query

      user_data = { 'username' => current_user.username }
      expect(results).to include(a_hash_including('approvedBy' => { 'nodes' => array_including(user_data) }))
    end

    include_examples 'N+1 query check'
  end
end
