# frozen_string_literal: true

require 'spec_helper'

describe ReleaseTools::Pre::ReleaseNote do
  subject(:release_note) do
    described_class.new(pipeline_id: pipeline.id, deploy_version: deploy_version)
  end

  let(:user) { create(:user) }
  let(:pipeline) { create(:pipeline, user: user) }
  let(:deploy_version) { '16.9.202402091206-d530de1fcd9.d71cbbdb4bc' }

  let(:definitions) do
    instance_spy(ReleaseTools::ReleaseManagers::Definitions)
  end

  let(:release_manager_schedule) do
    instance_spy(
      ReleaseTools::ReleaseManagers::Schedule,
      active_version: ReleaseTools::Version.new('16.9')
    )
  end

  let(:monthly_issue) do
    instance_spy(ReleaseTools::MonthlyIssue, url: 'http://test.com')
  end

  let(:release_manager_definition) do
    ReleaseTools::ReleaseManagers::Definitions::User.new(
      user.username,
      { 'gitlab.com' => user.username }
    )
  end

  before do
    allow(ReleaseTools::GitlabOpsClient)
      .to receive(:pipeline)
      .and_return(pipeline)

    allow(ReleaseTools::ReleaseManagers::Schedule)
      .to receive(:new)
      .and_return(release_manager_schedule)

    allow(ReleaseTools::ReleaseManagers::Definitions)
      .to receive(:new)
      .and_return(definitions)

    allow(definitions)
      .to receive(:find_user)
      .with(user.username, instance: :ops)
      .and_return(release_manager_definition)

    allow(ReleaseTools::MonthlyIssue)
      .to receive(:new)
      .and_return(monthly_issue)
  end

  describe '#execute' do
    it 'links the pipeline' do
      expect(ReleaseTools::GitlabClient)
        .to receive(:create_issue_note)
        .with(
          monthly_issue.project,
          hash_including(body: include("[pipeline](#{pipeline.web_url})"))
        )

      without_dry_run do
        release_note.execute
      end
    end

    it 'pings the release manager based on the pipeline' do
      expect(ReleaseTools::GitlabClient)
        .to receive(:create_issue_note)
        .with(monthly_issue.project, hash_including(body: include(user.username)))

      without_dry_run do
        release_note.execute
      end
    end

    context 'with dry run mode' do
      it 'does not create note' do
        expect(ReleaseTools::GitlabClient)
          .not_to receive(:create_issue_note)

        release_note.execute
      end
    end
  end
end
