require 'rails_helper'
require "#{Rails.root}/app/jobs/sync_jobs/position_table_sync_job.rb"

describe 'PositionTableSyncJob class' do
  before(:each) do
    foo_table = create(:table, name: 'Foo', full_name: 'EDW.Foo')
    create(:table, name: 'Bar', full_name: 'EDW.Bar')
    baz_table = create(:table, name: 'Baz', full_name: 'EDW.Baz')
    foo_pos = create(:position, position_code: 'FOO456', title: 'Foosballer')
    create(:position, position_code: 'BAR123', title: 'Barrister')
    baz_pos = create(:position, position_code: 'BAZ789', title: 'Bazooka...er')

    foo_pos.can_access_table = [foo_table]
    baz_pos.can_access_table = [baz_table]

    @data = [
      ['FOO456', 'EDW.Foo', 'Y'],
      ['BAR123', 'EDW.Bar', 'N'],
      ['BAZ789', nil, nil],
      ['FWEE00', 'EDW.Fwee', nil]
    ]

    # Don't upload anything to S3.
    allow_any_instance_of(PositionTableSyncJob).to receive(:text_upload)
  end

  context 'requires_data?' do
    it 'requires data' do
      expect(PositionTableSyncJob.requires_data?).to eq(true)
    end
  end

  context 'perform' do
    it 'sets the access_type property' do
      PositionTableSyncJob.new.perform(@data)
      foo_pos = Position.find_by(position_code: 'FOO456')
      expect(foo_pos.can_access_table.rels[0].access_type).to eq('Y')
      bar_pos = Position.find_by(position_code: 'BAR123')
      expect(bar_pos.can_access_table.rels[0].access_type).to eq('N')
    end

    it 'creates relationships' do
      PositionTableSyncJob.new.perform(@data)
      bar_pos = Position.find_by(position_code: 'BAR123')
      expect(bar_pos.can_access_table[0]).to eq(Table.find_by(full_name: 'EDW.Bar'))
    end

    it 'deletes relationships' do
      PositionTableSyncJob.new.perform(@data)
      baz_pos = Position.find_by(position_code: 'BAZ789')
      expect(baz_pos.can_access_table.count).to eq(0)
    end

    it 'does not create or delete any positions' do
      PositionTableSyncJob.new.perform(@data)
      expect(Position.all.count).to eq(3)
    end

    it 'does not create or delete any tables' do
      PositionTableSyncJob.new.perform(@data)
      expect(Table.all.count).to eq(3)
    end
  end
end
