# frozen_string_literal: true

require 'spec_helper'
require 'git/commands/maintenance/unregister'

# --config-file requires git 2.39.0, so these integration tests require 2.39.0
# even though the command itself supports 2.30.0.
RSpec.describe Git::Commands::Maintenance::Unregister, :integration,
               skip: unless_git('2.39.0', 'git maintenance unregister --config-file') do
  include_context 'in an empty repository'

  subject(:command) { described_class.new(execution_context) }

  # Redirect all global config writes to a temp file to avoid polluting ~/.gitconfig.
  # --config-file is also passed to the command itself to redirect the maintenance.repo write.
  #
  # The file handle is closed immediately after creation so that Windows does not hold an
  # exclusive lock on the file, which would prevent git from writing to it.
  let(:global_config) { Tempfile.new(['maintenance_global', '.conf']).tap(&:close) }
  let(:isolated_env) { { 'GIT_CONFIG_GLOBAL' => global_config.path } }

  after do
    global_config.close unless global_config.closed?
    global_config.unlink
  end

  describe '#call' do
    context 'when the command succeeds' do
      before do
        execution_context.command_capturing(
          'maintenance', 'register', '--config-file', global_config.path,
          raise_on_failure: false, env: isolated_env
        )
      end

      it 'returns a CommandLineResult' do
        result = command.call(config_file: global_config.path, env: isolated_env)

        expect(result).to be_a(Git::CommandLine::Result)
      end
    end

    context 'when the command fails' do
      it 'raises FailedError when not in a git repository' do
        FileUtils.rm_rf(File.join(repo_dir, '.git'))

        expect { command.call(config_file: global_config.path, env: isolated_env) }.to raise_error(Git::FailedError)
      end
    end
  end
end
