# frozen_string_literal: true

require 'spec_helper'

describe ReleaseTools::ReleaseEnvironment::DeployNotifier do
  subject(:notifier) do
    described_class.new(pipeline_url: pipeline_url,
                        environment_name: environment_name,
                        release_environment_version: release_environment_version)
  end

  let(:pipeline_url) { 'https://gitlab.com/gitlab-org/gitlab/-/pipelines/1' }
  let(:environment_name) { '16-10-stable' }
  let(:release_environment_version) { '16-10-stable-9dce3c3d' }
  let(:client) { stub_const('ReleaseTools::GitlabClient', spy) }
  let(:notification) { stub_const('ReleaseTools::Slack::ReleaseEnvironment::DeployNotification', spy) }

  let(:bridge) do
    create(
      :bridge_job,
      name: 'release-environments-deploy',
      downstream_pipeline: deploy_pipeline
    )
  end

  let(:bridges) { Gitlab::PaginatedResponse.new([bridge]) }

  let(:deploy_pipeline) do
    create(:pipeline, web_url: 'https://test.gitlab.net/deployer/-/pipelines/123')
  end

  before do
    allow(client)
      .to receive(:pipeline_bridges)
      .and_return(bridges)

    allow(ReleaseTools::Slack::ReleaseEnvironment::DeployNotification)
      .to receive(:new)
      .and_return(instance_double(ReleaseTools::Slack::ReleaseEnvironment::DeployNotification, execute: nil))
  end

  describe '#execute' do
    it 'sends a slack notification' do
      expect(notification)
        .to receive(:new)
        .with({ pipeline: deploy_pipeline, environment_name: environment_name, release_environment_version: release_environment_version })

      notifier.execute
    end

    context 'when the bridge is not found' do
      let(:bridges) { Gitlab::PaginatedResponse.new([]) }

      it 'does not send a slack notification' do
        expect(notification).not_to receive(:new)

        notifier.execute
      end

      it 'calls the pipeline bridges api at least twice' do
        expect(client)
          .to receive(:pipeline_bridges)
          .at_least(:twice)

        notifier.execute
      end
    end

    context 'when the downstream pipeline is not found' do
      let(:bridge) do
        create(
          :bridge_job,
          name: 'release-environments-deploy',
          downstream_pipeline: nil
        )
      end

      it 'does not send a slack notification' do
        expect(notification).not_to receive(:new)

        notifier.execute
      end
    end

    context 'when security mirror is used,' do
      let(:pipeline_url) { 'https://gitlab.com/gitlab-org/security/gitlab/-/pipelines/1' }

      it 'the security path is used' do
        expect(ReleaseTools::Project::GitlabEe).to receive(:security_path)

        notifier.execute
      end
    end
  end
end
