class Videos::BatchPublishService < ApplicationService
  Error = Class.new(StandardError)

  attr_reader :user, :params

  def initialize(user, params)
    @user   = user
    @params = params
  end

  def call
    video_params = Array.wrap(params[:videos]).compact
    return if video_params.blank?

    video_ids = []
    ActiveRecord::Base.transaction do
      video_params.each do |param|
        video = user.videos.find_by(uuid: param[:video_id])
        next if video.blank? || video.processing_video_apply.present?

        raise Error, '视频还未上传完成' if video.vod_uploading?

        video.title = param[:title].to_s.strip.presence || video.title
        video.apply_publish
        video.save!

        video.video_applies.create!

        video_ids << video.id
      end
    end

    BatchPublishVideoNotifyJob.perform_later(user.id, video_ids) if video_ids.present?
  end
end