const mongoose = require("mongoose")
const bcrypt = require("bcryptjs")

const UserSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true
    },
    email: {
      type: String,
      required: true,
      unique: true,
      lowercase: true,
      trim: true
    },
    password: {
      type: String,
      required: true
    },
    mobile: {
      type: String
    },
    registrationType:{
      type: String,
      enum:["web", "admin"],
      default: "web"
    },
    class: {
      type: String,
      enum: ["Class 9", "Class 10", "Class 11", "Class 12"]
    },
    stream:{
      type: String,
      enum: ["Medical", "Non-Medical", "Commerce", "Super-Medical"],
      default: null
    },
    goal:{
      type:String,
      enum:['CBSE', "NEET", "JEE", "Nursing", "CUET"],
    },
    batch:{
      type: mongoose.Schema.Types.ObjectId,
      ref:"Batch",
      default: null
    },
    role: {
      type: String,
      enum: ["admin", "student"],
      default: "student"
    },
    status: {
       type: String,
      enum: ["pending", "active", "frozen"],
      default: "pending"
    },
    profileCompleted: {
      type: Boolean,
      default: false
    },
    purchasedCourses:[
      {
        type: mongoose.Schema.Types.ObjectId,
        ref:"Course"
      }
    ],
    lockedCourses: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref:"Course"
      }
    ]
  },
  { timestamps: true, strict: true }
)

UserSchema.pre("save", async function () {
  if (!this.isModified("password")) return

  if (this.password.startsWith("$2b$")) return

  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
})

UserSchema.pre("save", function () {
  if (this.isModified("role") && !this.isNew) {
    throw new Error("Role cannot be changed directly")
  }
})

UserSchema.methods.comparePassword = function (enteredPassword) {
  return bcrypt.compare(enteredPassword, this.password)
}

module.exports = mongoose.model("User", UserSchema)
