# == Schema Information
#
# Table name: users
#
#  id              :integer          not null, primary key
#  name            :string
#  email           :string
#  role            :integer          default("member")
#  password_digest :string           not null
#  image           :string
#  phone           :string
#

class User < ApplicationRecord
  has_secure_password

  mount_uploader :image, ImageUploader

  has_many :offers, dependent: :nullify
  has_many :collections, dependent: :nullify
  has_many :tags, dependent: :nullify
  has_many :offer_tags, dependent: :nullify

  enum role: { member: 0, agent: 1, moderator: 2, admin: 3 }

  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }

  before_destroy :check_for_last_admin

  private

  def check_for_last_admin
    throw(:abort) if admin? && User.admin.count == 1
  end
end
