require "rails_helper"

describe GenerateReportsZipJob do
  let(:project)  { create(:project) }
  let(:download) { create(:download, project: project) }

  before do
    dir = Rails.root.join("spec", "fixtures", "files")
    files = ["bray_edl_100319-mp4_big-cue-sheet.xlsx", 
             "bray_edl_100319-mp4_discovery-cue-sheet.xlsx",
             "bray_edl_100319-mp4_gfx-cue-list.xlsx",
             "bray_edl_100319-mp4_issues-and-concerns.xlsx",
             "bray_edl_100319-mp4_production-elements-log.xlsx"]
    @zip_file_name = "#{project.name.parameterize}_#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}"
    allow_any_instance_of(ReportCollectionService).to receive(:build).and_yield(dir, files)
  end

  describe ".perform_later" do
    it "enqueues a background job for generating zip file" do
      expect {
        GenerateReportsZipJob.perform_later(project, download, @zip_file_name)
      }.to have_enqueued_job
    end
  end

  describe ".perform_now" do
    it "updates a download record and creates attachment for it" do
      GenerateReportsZipJob.perform_now(project, download, @zip_file_name)

      expect(download.project).to eq project
      expect(download.status).to eq "success"
      expect(download.file).to be_attached
    end

    context "When there are errors" do
      before do
        allow(ProjectsChannel).to receive(:broadcast_download_generation_update).with(download, I18n.t("report_downloads.download.failure"))
        allow_any_instance_of(ReportCollectionService).to receive(:build).and_raise(StandardError, "Reports not found")
      end
  
      it "updates status to 'failure' and sends user a notification" do
        GenerateReportsZipJob.perform_now(project, download, @zip_file_name)
  
        expect(download.status).to eq "failure"
        expect(ProjectsChannel).to have_received(:broadcast_download_generation_update).with(download, I18n.t("report_downloads.download.failure"))
      end
    end
  end

  after do
    path = Rails.root.join("spec", "fixtures", "files")
    File.delete("#{path}/#{@zip_file_name}.zip") if File.exists? "#{path}/#{@zip_file_name}.zip"
  end
end
