module Suppliers
  class ApplicationController < ::ApplicationController
    before_action :setup_employee_and_supplier!
    #load_and_authorize_resource
    attr_reader :current_supplier
    helper_method :current_supplier
    layout 'supplier/app'

    rescue_from 'RestClient::Conflict' do |e|
      #binding.pry
    end
    rescue_from CanCan::AccessDenied do |exception|
      respond_to do |format|
        format.html { redirect_to root_path, alert: 'Action forbidden'}
        format.json { render json: {errors: "403 Forbidden", ok: false}, status: :forbidden }
      end
    end

    # GET
    def employee_and_supplier
      # database optimization, preloading
      FlatKeys.as_nested_structure(Supplier::PRELOAD_INCLUDES).last.each do |relation_name, includes|
        relation_result = current_supplier.public_send(relation_name)
        relation_result.include_relations(includes) if relation_result.is_a?(Array)
      end
      render json: {
        employee: JSONAPI::Serializer.serialize(current_employee, serializer: Suppliers::EmployeeSerializer),
        supplier: JSONAPI::Serializer.serialize(current_supplier, serializer: Suppliers::SupplierSerializer, include: Supplier::PRELOAD_INCLUDES),
      }
    end

    def setup_employee_and_supplier!
      authenticate_employee!
      find_current_supplier!
      raise CanCan::AccessDenied unless current_supplier.present?
      current_employee.enrich_with_settings current_supplier.settings_for(current_employee)
      raise CanCan::AccessDenied unless current_employee.active?
      @current_ability = Suppliers::Ability.new( current_employee )
      run_after_authentication_hooks!
    end


    def find_current_supplier!
      return current_supplier if current_supplier.present?
      supplier_id = request.headers['HTTP_SUPPLIER_ID'].presence || session[:supplier_id].presence
      if supplier_id and supplier_id != 'null' and supplier_id != 'undefined' # crying face icon! but javascript nulls and ruby presence are not brothers
        supplier = Supplier.find(supplier_id)
        if supplier.employee_ids.include?(current_employee.id)
          @current_supplier = supplier
        else
          session[:supplier_id] = nil
          raise CanCan::AccessDenied unless current_employee.active?
        end
      else
        @current_supplier = current_employee.suppliers.first
        session[:supplier_id] = @current_supplier.try(:id)
      end
    end
  end
end
