const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const UserSchema = mongoose.Schema(
  {
    first_name: { type: String, required: [true, "First name is required"] },
    last_name: { type: String, required: [true, "Second name is required"] },
    username: {
      type: String,
      required: [true, "Username is required"],
      unique: true,
    },
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true,
      match: [
        /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
        "Please enter a valid email address",
      ],
    },
    agreement:{
        type:Boolean,
        require:[true, "Accept"]
    },
    password: {
      type: String,
      require: [true, "Password is required"],
      minLength: [6, "Password should be atleast 6 character"],
    },
    confirm_password: {
      type: String,
      require: [true, "Confirm Password field requird"],
      minLength: [6, "Confirm Password atleast 6 character"],
      validate: {
        validator: function (value) {
          return value === this.password;
        },
        message: "Passwords do not match",
      },
    },
  },
  {
    timestamps: true,
  }
);

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

const User = mongoose.model("User", UserSchema);

module.exports = User;
