class EmailVerificationToken < ApplicationRecord
  include Base::EmailVerificationToken

  audited

  belongs_to :user, foreign_key: :UserID, inverse_of: :email_verification_token

  delegate :school, to: :user

  before_validation :set_values, if: :new_record?

  after_create :send_verification_email

  validate :email_already_verified?

  def link
    "#{Rails.application.secrets.vue_base_url}/employee/account/info?token=#{token}"
  end

  def verify(user_token)
    if email_already_verified?
      error = 'This email address cannot be verified at this time. Please contact your Super User.'
      errors.add(:base, error)
      return false
    elsif new_record? || user_token != token
      errors.add(:base, 'The activation URL has expired.')
      return false
    end

    user.update(email_verified: true)
    destroy!
  end

  private
    def set_values
      self.email = user.email
      self.token = JsonWebToken.encode(user_id: user.id, email: email)
    end

    def send_verification_email
      EmailVerificationMailer.notify(self).deliver
    end

    def email_already_verified?
      address_verified = User.where(email: email, email_verified: true).exists?
      return false unless address_verified

      error = 'This email address cannot be verified at this time. Please contact your Super User.'
      errors.add(:base, error)
    end
end
