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

  attr_reader :user, :params

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

  def call
    validate!

    result = upload_video_result

    Video.create!(user: user, uuid: result['VideoId'], title: title, cover_url: params[:cover_url])

    result
  end

  private

  def title
    @_title ||= begin
      str = params.delete(:title).to_s.strip
      if str.length > 30
        "#{str[0, 15]}...#{str.reverse[0,10].reverse}"
      else
        str
      end
    end
  end

  def filename
    @_filename ||= params.delete(:file_name).to_s.strip
  end

  def validate!
    raise Error, '视频标题不能为空' if title.blank?
    raise Error, '源文件名不能为空' if filename.blank?
  end

  def upload_video_result
    AliyunVod::Service.create_upload_video(title, filename, params)
  rescue AliyunVod::Error => ex
    raise Error, ex.message || '获取视频上传凭证失败'
  end
end