class User < ApplicationRecord
  enum :role, guest: 'guest', member: 'member', admin: 'admin'

  validates :name, length: { maximum: 255 }
  validates :inheritance_code, presence: true, length: { maximum: 64 }
  validates :role, presence: true, inclusion: { in: roles.keys }

  has_many :created_posts,
           class_name: 'Post', foreign_key: :uploaded_user_id, dependent: :nullify
  has_one :setting, dependent: :destroy
  has_many :theme_slots, class_name: 'UserThemeSlot', dependent: :destroy
  has_many :user_ips, dependent: :destroy
  has_many :ip_addresses, through: :user_ips
  has_many :user_post_views, dependent: :destroy
  has_many :viewed_posts, through: :user_post_views, source: :post
  has_many :created_wiki_pages,
           class_name: 'WikiPage', foreign_key: :created_user_id, dependent: :nullify
  has_many :updated_wiki_pages,
           class_name: 'WikiPage', foreign_key: :updated_user_id, dependent: :nullify

  def viewed?(post) = user_post_views.exists?(post_id: post.id)

  def gte_member? = member? || admin?

  def banned? = banned_at.present?
  def ban! = banned? || update!(banned_at: Time.current)
  def unban! = update!(banned_at: nil)
end
