class Maintenance::CountryStateJob
  include Sidekiq::Worker

  def perform(id, klass)
    object = klass.constantize.find(id)
    @school = object.school

    case klass
    when 'Family'
      object.country_id = find_country(object.Country1)
      object.country_2_id = find_country(object.Country2)
      object.state = StateFinderService.call(object.state)
      object.state_2 = StateFinderService.call(object.state_2)
    when 'Contact'
      object.country_id = find_country(object.Country)
      object.state = StateFinderService.call(object.state)
    when 'FamilyMedical'
      object.physician_country_id = find_country('')
      object.dentist_country_id = find_country('')
      object.physician_state = StateFinderService.call(object.physician_state)
      object.dentist_state = StateFinderService.call(object.dentist_state)
    end
    object.save!(validate: false)
  end

  private
    def find_country(country)
      alpha = if country.length > 2
        ISO3166::Country.find_country_by_name(country)&.alpha2
      elsif country.length == 2
        country
      else
        @school.decorate.country_alpha2
      end

      IsoCountry.find_by(alpha2: alpha)&.id || 236
    end
end
