class User < ApplicationRecord
  enum :role, { user: "user", admin: "admin" }, suffix: true

  include PgSearch::Model
  pg_search_scope :pg_search, against: [ :lastname, :firstname, :email, :phone, :title ],
    using: { tsearch: { dictionary: "danish" } }

  has_secure_password
  has_many :verification_codes, dependent: :destroy

  before_destroy :dont_destroy_admin

  validates_presence_of :email
  validates_presence_of :password, on: :create
  validates_uniqueness_of :email
  validates_format_of :email, with: URI::MailTo::EMAIL_REGEXP

  normalizes :email, with: ->(email) { email.strip.downcase }

  validate :cant_change_admin, on: :update

  scope :enabled,   -> { where.not enabled_at: nil }

  scope :by_last_modified, ->(rev) { order(updated_at: rev ? :asc : :desc) }
  scope :by_name, ->(rev) { order(lastname: rev ? :desc : :asc, firstname: rev ? :desc : :asc) }
  scope :by_email, ->(rev) { order(email: rev ? :desc : :asc) }
  scope :by_title, ->(rev) { order(title: rev ? :desc : :asc) }

  scope :simple_search, ->(q) { pg_search(q) unless q.blank? }


  def su?
    email == "mattias@oncotype.dk"
  end


  def name
    return email if lastname.blank? and firstname.blank?
    [ firstname, lastname ].select { |v| !v.blank? }.join(" ")
  end


  def initials
    name.split(" ").map { |s| s[0] }.join("").mb_chars.upcase
  end


  def enabled?
    !self.enabled_at.nil?
  end


protected


  # Prevent the user admins from beeing changed
  def cant_change_admin
    user = self.class.find(self.id)
    errors.add(:email, I18n.t(:you_cant_change_the_email_on_this_user, scope: "users")) if user.su? and self.email != user.email
    errors.add(:email, I18n.t(:you_cant_change_this_on_this_user, scope: "users")) if user.su? and !self.admin_role? and self.role_changed?
    errors.add(:email, I18n.t(:you_cant_disable_this_user, scope: "users")) if user.su? and self.enabled_at.nil?
  end


  # Prevents the super user admin to be removed"
  def dont_destroy_admin
    raise I18n.t(:cant_destroy_this_user, scope: "users") if self.su?
  end
end
