import mongoose from 'mongoose'
import bcrypt from 'bcrypt'

// Define the user schema
const UserSchema = new mongoose.Schema({
  username: { type: String, unique: true },
  name: String,
  password: String
})

// Before saving the user to the database, hash the password.
UserSchema.pre('save', function (next) {
  if (this.isModified('password') || this.isNew) {
    bcrypt.genSalt(10, (err, salt) => {
      if (err) {
        return next(err)
      }
      bcrypt.hash(this.password, salt, (err, hash) => {
        if (err) {
          return next(err)
        }
        this.password = hash
        next()
      })
    })
  } else {
    return next()
  }
})

// Define a method to compare the hashed password.
UserSchema.methods.comparePassword = function (passwd, cb) {
  bcrypt.compare(passwd, this.password, (err, isMatch) => {
    if (err) {
      return cb(err)
    }
    cb(null, isMatch)
  })
}

const User = mongoose.model('User', UserSchema)

export default User
