class ContractDownloadsController < ApplicationController
  include ProjectContext

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

  include ProjectLayout

  def create
    authorize policy_scope(Download).create

    download = @project.downloads.create!(release_type: 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: 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: release_type.titleize))
    end

    GenerateContractsZipJob.perform_later(@project, download, release_type, release_ids, search_query, type_filter)
  end

  private

  def release_type
    params[:release_type]
  end

  def search_query
    params[:search_query]
  end

  def type_filter
    params[:type_filter]
  end

  def release_ids
    JSON.parse(params[:release_ids])
  rescue StandardError
    []
  end

  def release_name(release_type)
    release_type.constantize.model_name.plural
  end
end
