class Payjunction::Credential < ApplicationRecord
  include Encryptable
  audited

  belongs_to :school

  before_save :encrypt_password

  after_save :sync_accounts_and_terminals

  validates :username, presence: true
  validates :password, presence: true

  def sync_accounts_and_terminals
    Payments::Payjunction::SyncAccountsService.call(school)
    Payments::Payjunction::SyncTerminalsService.call(school)
  end

  def decrypted_password
    decrypt(password)
  end

  private
    def encrypt_password
      self[:password] = encrypt(password)
    end
end
