class ReleaseContractCollectionService
  def initialize(releases, folder_name)
    @releases = releases
    @folder_name = folder_name
  end

  def build
    Dir.mktmpdir { |dir|
      releases.each do |release|
        if release.native?
          next unless release.contract_template.present?
            
          contract = Contract.new(release)
          open("#{dir}/#{contract.filename}", 'wb') do |file|
            file << open(contract.to_pdf.path).read
          end
        else
          next unless release.contract.attached?
          
          open("#{dir}/" + release.contract.filename.to_s, 'wb') do |file|
            file << open(release.contract.service_url.to_s).read
          end
        end
      end

      files = Dir.entries("#{dir}/").select { |f| !File.directory? f }
      raise StandardError.new "Contracts or Contract Templates not found." unless files.any?
      yield(dir, files)
    }
  end

  private

  attr_reader :releases, :folder_name
end