namespace :materials do
  desc '素材同期'
  task sync: :environment do
    result = MaterialSyncRunner.sync_enabled!
    message = [
      "materials:sync imported=#{ result.imported }",
      "updated=#{ result.updated }",
      "unchanged=#{ result.unchanged }",
      "suppressed=#{ result.suppressed }",
      "failed=#{ result.failed }"
    ].join(' ')

    Rails.logger.info(message)
    puts message

    result.errors.each do |error|
      Rails.logger.warn(error.to_json)
      warn error.to_json
    end
  end

  namespace :thumbnails do
    desc '素材サムネールを補完'
    task backfill: :environment do
      counts = Hash.new(0)

      Material
        .with_attached_file
        .with_attached_thumbnail
        .find_each do |material|
          next unless material.file.attached?
          next if material.thumbnail.attached?

          result = MaterialThumbnailGenerator.generate!(material)
          counts[result] += 1
        end

      message =
          "materials:thumbnails:backfill " \
          "attached=#{ counts[:attached] } " \
          "no_file=#{ counts[:no_file] } " \
          "unsupported_content_type=#{ counts[:unsupported_content_type] } " \
          "generation_failed=#{ counts[:generation_failed] } " \
          "attach_failed=#{ counts[:attach_failed] } " \
          "file_not_found=#{ counts[:file_not_found] } " \
          "mini_magick_error=#{ counts[:mini_magick_error] }"
      Rails.logger.info(message)
      puts message
    end
  end
end
