Maintenance::PopulateMissingCountriesTask

Source code
# frozen_string_literal: true

class Maintenance::PopulateMissingCountriesTask < MaintenanceTasks::Task
  include DatadogTrace

  collection_batch_size(1000)

  def collection
    TreeNode.where.missing(:gds_profiles)
  end

  def process(tree_node)
    return log_missing_company_guid(tree_node) if tree_node.company_guid.blank?

    create_primary_gds_profile(tree_node)
  rescue StandardError => e
    log_process_error(tree_node, e)
  end

  delegate :count, to: :collection

  private

  def log_missing_company_guid(tree_node)
    Rails.logger.warn("TreeNode #{tree_node.name}:#{tree_node.id} does not have company_guid")
  end

  def create_primary_gds_profile(tree_node)
    data = fetch_data(tree_node.company_guid)
    tree_node.gds_profiles.primary.create!(country_code: extract_country_code(data), primary: true)
  end

  def log_process_error(tree_node, error)
    Rails.logger.warn(
      "Error in PopulateMissingCountriesTask, TreeNode #{tree_node.name}:#{tree_node.id}. #{error.message}"
    )
  end

  def fetch_data(company_guid)
    Api::AgentPortClient.client.company(company_guid)
  end

  def extract_country_code(data)
    data['CompanyProfileModel']['CompanyIdentity']['CountryCode']
  end
end