# frozen_string_literal: true

# spec/lib/gitlab/qa/component/pipeline_ops_spec.rb

require 'spec_helper'

module Gitlab
  module QA
    describe Component::PipelineOps do
      let(:pipeline_ops) { described_class.new }
      let(:docker) { instance_double(Gitlab::QA::Docker::Engine) }
      let(:gitlab) do
        instance_double(
          Gitlab::QA::Component::Gitlab,
          address: "http://gitlab.example.com",
          class: Struct.new(:name).new("Gitlab::QA::Component::Gitlab")
        )
      end

      let(:project_name) { 'test-project' }

      before do
        allow(gitlab).to receive_messages(docker: docker, name: 'gitlab-container')
      end

      describe '#start' do
        it 'executes pipeline command with correct parameters' do
          expect(docker).to receive(:exec).with('gitlab-container', /PROJECT_NAME='test-project' gitlab-rails runner/)
          expect(docker).to receive(:copy).with('gitlab-container', File.join(Dir.pwd, 'support', 'pipeline'), '/tmp/setup-scripts')
          pipeline_ops.start(gitlab, project_name)
        end
      end

      describe '#check_status' do
        context 'when pipeline succeeds' do
          it 'returns successfully' do
            expect(docker).to receive(:exec).and_return('success')
            expect { pipeline_ops.check_status(gitlab) }.not_to raise_error
          end
        end

        context 'when pipeline fails' do
          it 'raises an error' do
            expect(docker).to receive(:exec).and_return('failed')
            expect { pipeline_ops.check_status(gitlab) }.to raise_error(StandardError, "Pipeline failed.")
          end
        end
      end

      describe '#create_and_execute_pipeline_script' do
        let(:expected_src_path) { File.expand_path('../../../../support/pipeline', __dir__) }
        let(:expected_dest_path) { '/tmp/setup-scripts' }

        it 'copies pipeline scripts to the docker container' do
          expect(docker).to receive(:copy).with(
            'gitlab-container',
            expected_src_path,
            expected_dest_path
          )

          expect(docker).to receive(:exec).with(
            'gitlab-container',
            "PROJECT_NAME='#{project_name}' gitlab-rails runner #{expected_dest_path}/create_for_projectname.rb"
          )

          subject.send(:create_and_execute_pipeline_script, gitlab, project_name)
        end
      end
    end
  end
end
