RSpec.describe ERDL::Secrets do
  let(:dotenv_dottest) { File.expand_path('../../fixtures/.env.test', __FILE__) }

  describe '.load' do # WARNING: these examples mess with ENV!
    it 'loads ERDL_DOTENV when abspath is specified' do
      ClimateControl.modify ERDL_DOTENV: dotenv_dottest do
        ERDL::Secrets.load
        expect(ENV['COULD_EXIST']).to eq 'hi1'
        expect(ENV['DOES_NOT_EXIST']).to eq 'hi2'
      end
    end

    it 'loads ERDL_DOTENV when relpath is specified' do
      Dir.chdir(File.dirname(__FILE__)) do # change Dir.pwd to dir this spec file is located in
        ClimateControl.modify ERDL_DOTENV: '../fixtures/.env.test' do # WARNING: NOT the same relpath as the `let` above
          ERDL::Secrets.load
          expect(ENV['COULD_EXIST']).to eq 'hi1'
          expect(ENV['DOES_NOT_EXIST']).to eq 'hi2'
        end
      end
    end

    it 'loads a .env if it exists in the current working directory' do
      contents = File.read(dotenv_dottest)
      FakeFS do
        File.write('.env', contents)
        ClimateControl.modify ERDL_DOTENV: nil do
          ERDL::Secrets.load
          expect(ENV['COULD_EXIST']).to eq 'hi1'
          expect(ENV['DOES_NOT_EXIST']).to eq 'hi2'
        end
      end
    end

    it 'raises an error when an invalid ERDL_DOTENV is specified' do
      ClimateControl.modify ERDL_DOTENV: 'fake/path/to/nowhere' do
        expect { ERDL::Secrets.load }.to raise_error
      end
    end
  end

  describe '.ensure_all_present' do
    it 'raises an error when an ENV is missing' do
      ClimateControl.modify COULD_EXIST: 'value1', DOES_NOT_EXIST: nil do
        expect { ERDL::Secrets.ensure_all_present(dotenv_dottest) }.to raise_error # ENV['DOES_NOT_EXIST'] still missing
      end
    end

    it 'does not raise an error when all ENVs are present' do
      ClimateControl.modify COULD_EXIST: 'value1', DOES_NOT_EXIST: 'value2' do
        expect { ERDL::Secrets.ensure_all_present(dotenv_dottest) }.not_to raise_error
      end
    end
  end
end
