class GenerateContractsZipJob < ApplicationJob
  queue_as :default
  include Rails.application.routes.url_helpers
  include ActionView::Helpers::UrlHelper

  before_perform do |job|
    @project = job.arguments.first
    @download = job.arguments.second
    release_type = job.arguments.third
    @folder_name = "#{@project.name.parameterize}_#{get_release_name(release_type).gsub('_', '-')}"
    @download.update!(name: @folder_name, status: :pending)
  end

  def perform(project, download, release_type, release_ids)
    releases = project.public_send(get_release_name(release_type)).where(id: release_ids)

    ::ReleaseContractCollectionService.new(releases, @folder_name).build do |dir, files|
      zipfile_name = "#{dir}/#{@folder_name}.zip"
      Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
        files.each do |attachment|
          zipfile.add(attachment, File.join("#{dir}/", attachment))
        end
      end

      @download.file.attach(io: File.open(zipfile_name), filename: @folder_name)
    end
  rescue StandardError => e
    Rails.logger.error("Failed to generate download for project (##{project.id}) with release type #{release_type}\n" + e.message)
    
    @download.failure!
    ProjectsChannel.broadcast_download_generation_update(@download, I18n.t("contract_downloads.download.failure"))
  end

  after_perform do |job|
    if @download.pending? && @download.file.attached?
      @download.success!

      downloads_folder_link = link_to("Files > Downloads", project_downloads_path(I18n.locale, @project))
      download_button = link_to("Download", rails_blob_path(@download.file, disposition: "attachment", only_path: true), class: "btn btn-success", target: :_blank)
      ProjectsChannel.broadcast_download_generation_update(@download, I18n.t("contract_downloads.download.success", downloads_folder_link: downloads_folder_link, download_button: download_button, release_type: job.arguments.third.titleize))
    end
  end

  private

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