class WolfCore::ApplicationService

def call

def call
  process
rescue => e
  if e.instance_of?(WolfCore::ServiceException)
    return Result.failure(
      error: e.error.to_h.merge({ backtrace: e.backtrace })
    )
  end
  # Honeybadger.notify(e)
  return Result.failure(error: { message: e.message, backtrace: e.backtrace })
end

def get_salesforce_access_token

def get_salesforce_access_token
  result = WolfCore::SalesforceOauthService.new.call
  raise_failed_result(result)
  result.data.access_token
end

def get_salesforce_foreign_object(salesforce_access_token:, record_id:)

def get_salesforce_foreign_object(salesforce_access_token:, record_id:)
  foreign_object = salesforce_http_get(
    salesforce_access_token: salesforce_access_token,
    query: { calltype: 'getRecord', RecordId: record_id }
  )
  log_object "foreign object is"
  log_object foreign_object
  foreign_object
end

def get_wolf_token

def get_wolf_token
  response = http_post(
    query: { tenant: ENV['TENANT'] },
    url: "#{ENV['WOLF_PLATFORM_URL']}/api/v1/sign_in",
    body: {
      email: ENV['WOLF_ADMIN_EMAIL'],
      password: ENV['WOLF_ADMIN_PASSWORD']
    }
  )
  validate_http_response(
    response: response, message: 'Failed to get wolf token'
  )
  response_body = JSON.parse(response.body)
  wolf_token = response_body.dig('user', 'authentication_token')
  puts "wolf token is #{wolf_token}"
  wolf_token
end

def process

def process
  raise NotImplementedError
end

def raise_failed_result(result)

def raise_failed_result(result)
  return if result.success?
  raise_service_error(result.error.to_h)
end

def remove_non_permitted_parameters(params, allowed_params)

def remove_non_permitted_parameters(params, allowed_params)
  permitted = params.slice(*allowed_params)
  if permitted.blank?
    raise_service_error({ message: "There are not permitted parameters"})
  end
  return permitted
end

def salesforce_http_get(salesforce_access_token:, query: nil)

def salesforce_http_get(salesforce_access_token:, query: nil)
  response = http_get(
    url: ENV['SALESFORCE_URL'],
    headers: { 'Authorization' => "Bearer #{salesforce_access_token}" },
    query: query
  )
  validate_salesforce_response(response)
  JSON.parse(response.parsed_response)
end

def validate_presence(object, message)

def validate_presence(object, message)
  return if object.present?
  raise_service_error({ message: message })
end

def validate_salesforce_response(response)

def validate_salesforce_response(response)
  return if response.code == 200
  message = JSON.parse(response.body).first['message']
  raise_service_error({ message: message })
end