class MarketoWorker
  include Sidekiq::Worker

  attr_reader :marketo_client

  def self.enqueue(provider, user, options = {})
    perform_async(provider.as_json, user.as_json, options.as_json)
  end

  def self.enabled?
    System::Application.config.three_scale.marketo_enabled
  end

  def self.config
    System::Application.config.three_scale.marketo
  end

  def self.marketo_client
    MarketoClient.new(config)
  end

  def initialize
    @marketo_client = self.class.marketo_client
  end

  def perform(account_attributes, user_attributes, mkt_cookie)
    return unless self.class.enabled?

    attributes = build_attributes(account_attributes, user_attributes)
    lead_id = marketo_client.create_lead(attributes)

    if mkt_cookie.present?
      marketo_client.associate_lead(lead_id, mkt_cookie)
    else
      Rails.logger.error("No cookie was provided, skipping lead association")
    end
  end

  def build_attributes(account_attributes, user_attributes)
    account = account_attributes.fetch('account')
    user = user_attributes.fetch('user')
    extra_fields = account.fetch('extra_fields', {})
    settings = account.fetch('settings', {})

    {
      firstName: user['first_name'],
      lastName: user['last_name'],
      email: user['email'],
      leadSource: 'signup',
      Company: account['org_name'] ,
      MT_account_id__c_contact: account['id'],
      MT_user_id__c: user['id'],
      MT_heroku_id__c: settings['heroku_id'],
      MT_domain_capture__c: account['self_domain'],
      Signup_Source_Detail__c: (extra_fields['Signup_origin'] || extra_fields['partner'] || 'unknown'),
      API_Purpose_3s__c:  (extra_fields['API_Purpose_3s__c'] || ''),
      API_Status_3s__c:  (extra_fields['API_Status_3s__c'] || ''),
      API_Type_3s__c:  (extra_fields['API_Type_3s__c'] || '')
    }
  end
end
