# frozen_string_literal: true

require 'spec_helper'

describe ReleaseTools::Pre::Notifier do
  subject(:notifier) do
    described_class.new(pipeline_id: 123, deploy_version: deploy_version)
  end

  let(:deploy_version) { '16.9.202402091206-d530de1fcd9.d71cbbdb4bc' }
  let(:client) { stub_const('ReleaseTools::GitlabOpsClient', spy) }
  let(:notification) { stub_const('ReleaseTools::Slack::PreNotification', spy) }

  let(:bridge) do
    create(
      :bridge_job,
      name: 'pre:deploy',
      downstream_pipeline: deployer_pipeline
    )
  end

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

  let(:deployer_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::PreNotification)
      .to receive(:new)
      .and_return(instance_double(ReleaseTools::Slack::PreNotification, execute: nil))
  end

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

      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: 'pre:deploy',
          downstream_pipeline: nil
        )
      end

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

        notifier.execute
      end
    end
  end
end
