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"}, status: :forbidden }
      end
    end

    def setup_employee_and_supplier!
      authenticate_employee!
      find_current_supplier!
      return 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?
      if session[:supplier_id]
        supplier = Supplier.find(session[:supplier_id])
        if supplier.employee_ids.include?(current_employee.id)
          @current_supplier = supplier
        else
          render nothing: true, status: :unauthorized
        end
      else
        @current_supplier = current_employee.suppliers.first
        session[:supplier_id] = @current_supplier.try(:id)
      end
    end
  end
end
