import mongoose from "mongoose";
import bcrypt from 'bcryptjs';

const userSchema = new mongoose.Schema({
    username:{
        type:String,
        required:true,
        unique: true,
    },
    email:{
        type:String,
        required:true,
        unique:true,
    },
    password:{
        type:String,
        required:true,
    }
},{timestamps:true}
);

userSchema.pre('save', async  function (){
    if(!this.isModified("password")) return;
    const salt = await bcrypt.genSalt(10);
    this.password= await bcrypt.hash(this.password, salt);
});

userSchema.methods.matchPassword= async function (enteredPassword){
    return await bcrypt.compare(enteredPassword, this.password);
}

const User = mongoose.model("user",userSchema);

export default  User;

