require 'bcrypt'

class User < ActiveRecord::Base
  has_many :trips

  validates :email, presence: true, uniqueness: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/ }
  validates :password_hash, presence: true
  validates :first_name, :last_name, presence: true

  include BCrypt

  def password
    @password ||= Password.new(password_hash)
  end

  def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
  end

  def self.authenticate(email, password)
    @user = User.find_by(email: email)
    return nil if @user.nil?
    @user.password == password ? @user : nil
  end

  def full_name
    self.first_name + " " + self.last_name
  end
end
