# frozen_string_literal: true
module Panel
  #
  class HomeController < PanelController
    skip_load_resource
    skip_authorize_resource
    def index
      # Last day expedients
      last_day = Date.current - 1.day
      @last_day_expedients = Expedient
        .accessible_by(current_ability, :read)
        .where(received_at: last_day.beginning_of_day .. last_day.end_of_day)
        .reorder(received_at: :desc)
        .limit(10)
      # Current year expedients by branches
      if current_user.one_institution?
        @current_year_expedients = Expedient
          .accessible_by(current_ability, :read)
          .select(:id, :branch_id)
          .where(received_at: Time.current.beginning_of_year .. Time.current.end_of_year)
          .includes(:branch)
          .group_by{|e| e.branch.try(:name)}
          .sort_by{|k, v| k.to_s}.to_h
      end
      # Managements by kind and category name
      mids = Management.accessible_by(current_ability, :read).pluck(:id)
      @management_categories = Management
        .where(id: mids)
        .select("managements.kind AS kind, management_categories.name AS name, count(managements.kind) AS total")
        .joins(:management_category)
        .group('managements.kind, management_categories.name')
        .order('managements.kind asc, management_categories.name asc, count(managements.kind) desc')
      # Expedients expired without communication
      three_business_days_ago = 3.business_days.before(Date.current)
      @expired_expedients = Expedient
        .accessible_by(current_ability, :read)
        .where(state: 'new')
        .where('received_at < ?', three_business_days_ago)
        .order(received_at: :desc)
        .limit(5)
      # Open managements expired
      @expired_managements = Management
        .where(id: mids)
        .where(state: 'process')
        .where(deadline_at: Date.current .. 3.business_days.from_now)
        .order(deadline_at: :asc)
        .limit(5)
      # Expedients total by institution / branch
      # unless current_user.one_institution?
      #   # TODO change later with a counter_cache column
      #   @by_institutions = Institution.accessible_by(current_ability, :read)
      #     .includes(:expedients, branches: :expedients)
      # end
    end
  end
end
