class GenerateReportsZipJob < 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
    @download.update!(status: :pending)
  end

  def perform(project, download, folder_name)
    videos = project.videos.reports_published

    ::ReportCollectionService.new(videos).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})\n" + e.message)
    
    @download.failure!
    ProjectsChannel.broadcast_download_generation_update(@download, I18n.t("report_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("report_downloads.download.success", downloads_folder_link: downloads_folder_link, download_button: download_button))
    end
  end
end
