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

  attr_reader :video_apply, :video, :user, :params

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

  def call
    reason = params[:reason].to_s.strip
    raise Error, '原因不能为空' if reason.blank?
    raise Error, '该状态下不能进行此操作' unless video_apply.may_refuse?

    ActiveRecord::Base.transaction do
      video_apply.reason = reason
      video_apply.refuse
      video_apply.save!

      video.refuse!

      # 将消息改为已处理
      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: 0,
                   container_id: video.id, container_type: 'Video',
                   tiding_type: 'System', status: 2, extra: video_apply.reason)
  end
end