class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    # alias_action :create, :read, to: :read_and_create
    # alias_action :update, :read, to: :read_and_update
    # alias_action :create, :read, :update, to: :read_create_and_update
    if user.has_role?("admin")
      can :manage, :all
    elsif user.has_role?("oir")
      can :manage, Expedient, institution_id: user.institution_ids
      can :create, Expedient
      cannot :modify, Expedient, institution: { can_edit: false }
      can :manage, Management, expedient: { institution_id: user.institution_ids }
      cannot :modify, Management, expedient: { institution: { can_edit: false } }
      can :read, ManagementCategory, institution_id: user.institution_ids
      # can :create, ManagementCategory
      can :manage, Branch, institution_id: user.institution_ids
      can :create, Branch
      can :manage, EntryWay, institution_id: user.institution_ids
      can :read, EntryWay, institution_id: nil
      can :create, EntryWay
      can :read_update_and_create, [Asset, Comment, Event]
      can [:read, :update, :settings], Institution, id: user.institution_ids
      can :read, Role
      can :read, :statistic
      # Users
      can [:create], User
      can [:read, :update, :destroy], User, id: User.by_institution(user.institution_ids).pluck(:id)
      cannot :destroy, User, id: user.id
      can :manage, Event
    elsif user.has_role?("oir_local")
      can :manage, Expedient, branch_id: user.branch_ids
      can :create, Expedient
      cannot :modify, Expedient, branch: { can_edit: false }
      can :read, Management, id: Management.for_assigned(user.id)
      can :manage, Management, expedient: { branch_id: user.branch_ids }
      cannot :modify, Management, expedient: { branch: { can_edit: false } }
      can :read, Expedient, id: Expedient.for_assigned(user.id)
      can [:read, :update, :settings], Branch, id: user.branch_ids
      # Users
      can [:create], User
      can [:read, :update, :destroy], User, id: User.by_branch(user.branch_ids).pluck(:id)
      can :read, :statistic
      cannot :destroy, User, id: user.id
      can :manage, Event
    else #administrative_unit
      can :read, Management, id: Management.for_assigned(user.id)
      can :read, Expedient, id: Expedient.for_assigned(user.id)
      can :read, Institution, id: user.institution_ids
      # can :read_and_create, Comment
    end
  end
end
