# frozen_string_literal: true

describe GraphQLSchemaCompatibility::CheckRunService do
  include_context "github request mocking"

  let(:repo_owner) { 'salsify' }
  let(:repo_name) { 'my-service' }
  let(:repo) { "#{repo_owner}/#{repo_name}" }
  let(:repo_id) { 'my-repo-id' }
  let(:check_run_service) { described_class.new(github_token) }

  before do
    variables = {
      owner: repo_owner,
      name: repo_name
    }
    response_data = {
      repository: {
        id: repo_id
      }
    }
    stub_github_request(
      query: described_class::ResolveRepositoryIdQuery,
      variables: variables,
      response_data: response_data
    )
  end

  describe "#create_check_run" do
    let(:check_run_id) { 'my-check-run-id' }
    let(:check_name) { 'my-check' }
    let(:sha) { 'my-sha' }

    before do
      response_data = {
        createCheckRun: {
          checkRun: {
            id: check_run_id
          }
        }
      }
      variables = {
        repositoryId: repo_id,
        name: check_name,
        sha: sha
      }

      stub_github_request(
        query: described_class::CreateCheckRunQuery,
        variables: variables,
        response_data: response_data
      )
    end

    it "returns the id of the new check run" do
      actual_check_run_id = check_run_service.create_check_run(repo: repo, name: check_name, sha: sha)
      expect(actual_check_run_id).to eq(check_run_id)
    end
  end

  describe "#complete_check_run" do
    let(:check_run_id) { 'my-check-run-id' }
    let(:conclusion) { :failure }
    let(:title) { 'My Title' }
    let(:summary) { 'My Summary' }
    let(:annotation) do
      GraphQLSchemaCompatibility::Annotation.new(
        path: 'my-path',
        line: 7,
        level: :warning,
        title: 'My Annotation Title',
        message: 'My annotation message'
      )
    end

    before do
      response_data = {
        updateCheckRun: {
          checkRun: {
            id: check_run_id
          }
        }
      }

      variables = {
        repositoryId: repo_id,
        id: check_run_id,
        conclusion: 'FAILURE',
        output: {
          title: title,
          summary: summary,
          annotations: [annotation.to_graphql_input]
        }
      }

      stub_github_request(
        query: described_class::CompleteCheckRunQuery,
        variables: variables,
        response_data: response_data
      )
    end

    it "returns the id of the completed check run" do
      actual_check_run_id = check_run_service.complete_check_run(
        repo: repo,
        id: check_run_id,
        conclusion: conclusion,
        title: title,
        summary: summary,
        annotations: [annotation]
      )
      expect(actual_check_run_id).to eq(check_run_id)
    end
  end
end
