class SetTagsForReleasableJob < ApplicationJob
  queue_as :default

  before_perform do |job|
    releasable = job.arguments.first
    releasable.tagging_started!
  end

  def perform(releasable)
    tags = releasable.photos.flat_map do |photo|
      BrayniacAI::Tag.create(bucket_name: bucket_name, object_name: photo.key).to_a
    end

    releasable.update! \
      internal_tag_list: tags,
      tagging_status: :finished

  rescue StandardError => e
    releasable.tagging_failed!
    Rails.logger.error("Failed to attach tags to AppearanceRelease(##{releasable.id})\n" + e.message)
  end

  private

  def bucket_name
    ENV['AWS_BUCKET']
  end
end
