require 'spec_helper'

describe Region do

  include UsesTempFiles

  REGION_CODES_CSV = 'region_codes.csv'

  in_directory_with_file(REGION_CODES_CSV)

  let(:region_codes_data) {tiny_maxmind_dataset[:region_codes]}

  before(:each) do
    content_for_file(to_csv(region_codes_data))
  end

  describe "import_from_region_codes" do

    after(:all) do
      # anything that calls after_maxmind_import seems to break transactions (DatabaseCleaner)
      create_phony_database
    end

    it "succeeds" do
      Region.import_from_region_codes(file: REGION_CODES_CSV)

      result = Region.connection.execute("SELECT * FROM regions_copied")
      result.ntuples.should == 1
      row1 = region_codes_data[0]
      result[0]['region'].should == row1[REGIONCODES_REGIONCODE_INDEX]
      result[0]['regionname'].should == row1[REGIONCODES_REGIONNAME_INDEX]
      result[0]['countrycode'].should == row1[REGIONCODES_COUNTRYCODE_INDEX]

      list_indexes('regions_copied').should =~ [Region::COPIED_COUNTRY_CODE_INDEX_NAME, Region::COPIED_UNIQUE_INDEX_NAME]

      # verify we can swap out tables
      Region.after_maxmind_import

      table_exists?('regions_copied').should be_false
      result = Region.connection.execute("SELECT * FROM regions")
      result.ntuples.should == 1
      list_indexes('regions').should =~ [Region::COUNTRY_CODE_INDEX_NAME, Region::UNIQUE_INDEX_NAME]
    end
  end
end

