class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
    #
    # The first argument to `can` is the action you are giving the user
    # permission to do.
    # If you pass :manage it will apply to every action. Other common actions
    # here are :read, :create, :update and :destroy.
    #
    # The second argument is the resource the user can perform the action on.
    # If you pass :all it will apply to every resource. Otherwise pass a Ruby
    # class of the resource.
    #
    # The third argument is an optional hash of conditions to further filter the
    # objects.
    # For example, here the user can only update published articles.
    #
    #   can :update, Article, :published => true
    #
    # See the wiki for details:
    # https://github.com/ryanb/cancan/wiki/Defining-Abilities
    alias_action :create, :read, :update, to: :cru

    user ||= User.new

    if user.usertype == "A"
      # Cajas registradoras
      can :read, [CashRegister, Purchase, PaymentMethod, ProductsReturn]
      # Categorias
      can :manage, [Category, Customer, BillingInformation, Expensesconcept, Pointsale, Product, Supplier, Unit, Sale, PosConfig, Purchase, SpecialPrice, ProductWaste, Seller, CashOut, Transfer, Expense, User, Warehouse, Commission, Sellerscommission]

      cannot [:create, :delete, :liquidate_reserve], Sale

    elsif user.usertype == "G"
      # Cajas registradoras
      can :manage, [CashRegister, Purchase, Product, PrePurchase, Seller, Sale, Expense, ProductWaste, Transfer, OpenCashRegister, CashOut, Supplier, Customer, Credit, CreditPayment, Commission, Sellerscommission, ProductsReturn, Category]
      # Categorias
      can :read, [SpecialPrice, Expensesconcept, Credit, CreditPayment, Unit]
      # Clientes
      can :cru, [Customer, BillingInformation, Pointsale, User, Warehouse, Credit, CreditPayment, Commission, Sellerscommission]

    elsif user.usertype == "C"
      # Cajas registradoras
      can :read, [Product, Pointsale, Customer, BillingInformation, Seller, SpecialPrice, Expensesconcept, Credit, CreditPayment]
      # ventas
      can :cru, [Credit, CreditPayment]

      can :manage, [CashRegister, PreSale, OpenCashRegister, Sale, Customer, Credit, CreditPayment, CashOut, Expense, Transfer, ProductsReturn, ProductWaste]

    elsif user.usertype == "S"
      can :read, [CashRegister, Product, Pointsale, Customer, BillingInformation, Seller, SpecialPrice, Expensesconcept]

      can :manage, [Transfer, ProductWaste]
    end
  end
end
