class ContractDownloadsController < ApplicationController
  include ProjectContext

  before_action :set_project, only: [:index, :create]

  include ProjectLayout

  def create
    authorize policy_scope(Download).create
    fetch_releases
    
    download = @project.downloads.create!(release_type: params[:release_type])
    other_downloads_in_progress = @project.downloads.unfinished_desc_order.offset(1)

    if other_downloads_in_progress.any?
      in_progress_downloads_details = render_to_string "_other_pending_downloads", locals: { downloads: other_downloads_in_progress, release_type: params[:release_type] }, :layout => false
      ProjectsChannel.broadcast_download_generation_update(download, in_progress_downloads_details)
    else
      ProjectsChannel.broadcast_download_generation_update(download, I18n.t("contract_downloads.download.pending", release_type: params[:release_type].titleize))
    end

    GenerateContractsZipJob.perform_later(@project, download, params[:release_type], @releases.ids)
  end

  private

  def fetch_releases
    @releases = policy_scope(@project.public_send(releases))
  end

  def releases
    params[:release_type].constantize.model_name.plural
  end
end
