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

  attr_reader :video_apply, :video, :user

  def initialize(video_apply, user)
    @video_apply = video_apply
    @video       = video_apply.video
    @user        = user
  end

  def call
    raise Error, '该状态下不能进行此操作' unless video_apply.may_agree? && video.may_publish?

    ActiveRecord::Base.transaction do
      video_apply.agree!

      video.published_at = Time.now
      video.publish
      video.save!

      # 将消息改为已处理
      Tiding.where(container_id: video.id, container_type: 'Video', tiding_type: 'Apply', status: 0).update_all(status: 1)
      notify_video_author!
    end
  end

  private

  def notify_video_author!
    Tiding.create!(user_id: video.user_id, trigger_user_id: 1,
                   container_id: video.id, container_type: 'Video',
                   tiding_type: 'System', status: 1)
  end
end