# frozen_string_literal: true

require 'schema_dev/gem'

describe SchemaDev::Gem do
  around(:each) do |example|
    in_tmpdir do
      suppress_stdout_stderr do
        example.run
      end
    end
  end

  Given(:user_name) { 'My Name' }
  Given(:user_email) { 'my_name@example.com' }

  Given do
    allow_any_instance_of(described_class).to receive(:`).with('git config user.name').and_return user_name
    allow_any_instance_of(described_class).to receive(:`).with('git config user.email').and_return user_email
  end

  describe 'builds' do
    Given do
      stub_request(:get, 'https://rubygems.org/api/v1/versions/schema_plus_core.json').to_return body: JSON.generate([
        { number: '1.0.0.pre', prerelease: true },
        { number: '0.2.1' },
        { number: '0.1.2' },
        { number: '0.1.1' },
      ])
    end

    When { described_class.build gem_name }

    When(:gemspec) { File.read "#{gem_name}/#{gem_name}.gemspec" }
    When(:readme) { File.read "#{gem_name}/README.md" }

    Invariant { expect(readme).to include '<!-- These lines are auto-generated by schema_dev based on schema_dev.yml -->' }
    Invariant { expect(readme).to include '<!-- These lines are auto-inserted from a schema_dev template -->' }

    Invariant { expect(gemspec).to include "'schema_plus_core', '~> 0.2', '>= 0.2.1'" }
    Invariant { expect(gemspec).to match %r{authors.*#{user_name}} }
    Invariant { expect(gemspec).to match %r{email.*#{user_email}} }

    context 'when a flat gem' do
      Given(:gem_name) { 'new_gem' }
      Then { expect(gemspec).to include "require 'new_gem/version'" }
      Then { expect(File.read('new_gem/lib/new_gem.rb')).to include 'SchemaMonkey.register NewGem' }
    end

    context 'when a subdir gem' do
      Given(:gem_name) { 'schema_plus_new_gem' }
      Then { expect(gemspec).to include "require 'schema_plus/new_gem/version'" }
      Then { expect(File.read('schema_plus_new_gem/lib/schema_plus_new_gem.rb')).to include "require_relative 'schema_plus/new_gem'" }
      Then { expect(File.read('schema_plus_new_gem/lib/schema_plus/new_gem.rb')).to include 'SchemaMonkey.register SchemaPlus::NewGem' }
    end
  end

  describe 'complains' do
    context 'when no git user.name' do
      Given(:user_name) { '' }
      Then { expect { described_class.build('NewGem') }.to raise_error SystemExit, /who are you/i }
    end

    context 'when in git worktree' do
      Given { expect_any_instance_of(described_class).to receive(:system).with(/^git rev-parse/).and_return true }
      Then { expect { described_class.build('NewGem') }.to raise_error SystemExit, /\bgit\b/ }
    end

    context 'when gem directory exists' do
      Given { FileUtils.touch 'new_gem' }
      Then { expect { described_class.build('NewGem') }.to raise_error SystemExit, /exists/ }
    end
  end
end