# == Schema Information
#
# Table name: trace_users
#
#  id         :integer          not null, primary key
#  user_id    :integer
#  username   :string(255)
#  password   :string(255)
#  unit       :string(255)
#  telnumber  :string(255)
#  email      :string(255)
#  name       :string(255)
#  token      :text(65535)
#  expired_at :datetime
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
# Indexes
#
#  index_trace_users_on_user_id  (user_id)
#

# 代码溯源 用户
class TraceUser < ApplicationRecord

  belongs_to :user


  def build_self_data
    return if user.nil? 

    self.username = user.login 
    self.password = SecureRandom.hex
    self.unit = user.custom_department.blank? ? 'Osredm' : user.custom_department
    self.telnumber = user.phone || ""
    self.email = user.mail 
    self.name = user.nickname.blank? ? user.login : user.nickname 

    self
  end


  def build_token 
    return if username.blank? || password.blank? || unit.blank? || email.blank? || name.blank? 

    response = Trace::AddUserService.call(username, password, unit, telnumber, email, name)
    self.token = response[1]['token']
    self.expired_at = Time.now + 1.hours
  end

  def refresh_token 
    return if username.blank? || password.blank? || unit.blank? || email.blank? || name.blank? 

    response = Trace::LoginService.call(username, password)
    self.token = response[1]['token']
    self.expired_at = Time.now + 1.hours
  end
end
