require 'three_scale/error_reporting_ignore_enduser'

class DeveloperPortal::AccessCodesController < ApplicationController
  include ::ThreeScale::ErrorReportingIgnoreEnduser
  error_reporting_ignore_enduser

  #TODO: if AccessCodeProtection would be splitted in more modules this wouldn't be needed

  include SiteAccountSupport
  include AccessCodeProtection
  skip_before_filter :protect_access

  include Liquid::TemplateSupport
  include Liquid::Assigns

  layout false

  def show
    if params[access_code_param].presence == access_code
      cookies[access_code_param] = params[access_code_param]

      return_to = params[:return_to] || session[:return_to]

      return_url = if return_to.blank? || return_to == access_code_path
                     root_url(cms_params)
                   else
                     safe_return_to(return_to)
                   end

      session[:return_to] = nil

      redirect_to return_url
    else
      store_location if request.path != access_code_path && !session[:return_to]
    end
  end

  private

  def cms_params
    params.slice(:cms_token, :cms)
  end

  def safe_return_to(url)
    uri = URI(url)
    uri.query = cms_params.to_query
    uri.select(:path, :query).compact.join('?')
  end
end
