class DownloadsController < ApplicationController
  include ProjectContext

  before_action :set_project, only: [:index, :destroy]
  before_action :set_download, only: [:destroy]

  include ProjectLayout

  def index
    @downloads = filtered_downloads.paginate(page: params[:page])
  end

  def destroy
    authorize @download
    @project = @download.project

    if @download.destroy
      redirect_to [@project, :downloads], alert: "The download has been deleted"
    end
  end

  def project_for_layout
    @project || @download.project
  end

  private

  def downloads
    authorize policy_scope(@project.downloads)
  end

  def downloads_desc_order
    downloads.order("created_at DESC")
  end

  def filtered_downloads
    params[:query].present? ? downloads_desc_order.search(params[:query]) : downloads_desc_order
  end

  def set_download
    @download = policy_scope(@project.downloads).find(params[:id])
  end
end
