require 'securerandom'
class ZoomUser < ApplicationRecord
  has_many :zoom_meetings, dependent: :nullify

  enum tier: [:basic, :pro]

  after_create :create_api_user, if: -> { api_id.nil? }
  before_destroy :abort_destroy

  scope :current_account, -> { where(account_number: ZoomGateway.ACCOUNT_NUMBER) }
  scope :free, -> { where.not(id: ZoomMeeting.active.pluck(:zoom_user_id)) }

  def create_api_user
    retries ||= 0
    self.api_id = gateway.create_host(self.class.generate_api_email)
    self.account_number = ZoomGateway.ACCOUNT_NUMBER
    save
  rescue ZoomGateway::UserAlreadyExists => e
    retries += 1
    if retries < 3
      retry # new api email will be generated automatically
    else
      raise e
    end
  end

  def delete_api_user
    gateway.delete_host(self.api_id)
    self.api_id = nil
    save
  end

  def current_account?
    account_number == ZoomGateway.ACCOUNT_NUMBER
  end

  # Static methods
  class << self
    def generate_api_email
      "host#{SecureRandom.random_number(10000)}@directme"
    end

    def for_new_meeting
      user = public_send(ZoomGateway.USER_TYPE_NAME).current_account.free.first
      if user.nil?
        user = public_send(ZoomGateway.USER_TYPE_NAME).current_account.create
      end
      user
    end
  end

  private

  def abort_destroy
    if api_id.present?
      errors.add(:base, "You can't destroy ZoomUser before explicitly deleting it through API.")
      throw(:abort)
    end
  end

  def gateway
    @gateway ||= ZoomGateway.new
  end
end
