module AnalyticsHelper
  def javascript_include_analytics_js
    return unless analytics_enabled?

    if segment_client_key.present?
      javascript_tag analytics_js_snippet, nonce: true
    end
  end

  def identify_user_for_analytics(user)
    return unless analytics_enabled?

    if user.present?
      javascript_tag identify_user_snippet(user.id, user.email, user.full_name), nonce: true
    end
  end

  private

  def analytics_enabled?
    ENV["ENABLE_ANALYTICS"] == "true"
  end

  def segment_client_key
    ENV["SEGMENT_CLIENT_KEY"]
  end

  def analytics_js_snippet
    <<~SNIPPET
      !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var t=analytics.methods[e];analytics[t]=analytics.factory(t)}analytics.load=function(e,t){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src="https://cdn.segment.com/analytics.js/v1/"+e+"/analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(n,a);analytics._loadOptions=t};analytics.SNIPPET_VERSION="4.1.0";
        analytics.load("#{segment_client_key}");
        analytics.page();
      }}();
    SNIPPET
  end

  def identify_user_snippet(id, email, name)
    <<~SNIPPET
      analytics.identify('#{id}', {
        email: '#{email}',
        name: '#{name}'
      });
    SNIPPET
  end
end
