const mongoose = require("mongoose");
const { isEmail } = require("validator");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    minlength: [4, "Name must be at least 4 characters long"],
  },
  username: {
    type: String,
    minlength: [4, "Username must be at least 4 characters long"],
    unique: [true, "This username is already taken."],
    required: [true, "Username is required."],
  },
  phoneNumber: {
    type: String,
  },
  email: {
    type: String,
    validate: [isEmail, "Please enter a valid email address."],
    lowercase: true,
  },
  photo: {
    type: String,
    default: "profile-placeholder.jpg",
  },
  role: {
    type: String,
    enum: ["admin", "administrator", "customer"],
    default: "customer",
  },
  password: {
    type: String,
    minlength: 8,
    select: false,
  },
  workfield: { type: String },
  emailStatus: {
    type: String,
    enum: ["verified", "notVerified"],
    default: "notVerified",
  },
  website: String,
  passwordChangedAt: Date,
  emailCode: {
    type: String,
    select: false,
  },
  company: String,
  emailCodeExpires: Date,
  resetPasswordCode: String,
  resetPasswordCodeExpires: Date,
  createdAt: {
    type: Date,
    default: Date.now(),
  },
  active: {
    type: Boolean,
    default: true,
  },
});

// Automatically set creation date
userSchema.pre("save", function (next) {
  this.createdAt = Date.now();
  next();
});

// Check if password has been changed after token was issued
userSchema.methods.changedPasswordAfter = function (JWTTimestamp) {
  if (this.passwordChangedAt) {
    const changedTimestamp = parseInt(
      this.passwordChangedAt.getTime() / 1000,
      10
    );
    return JWTTimestamp < changedTimestamp;
  }
  return false; // Not changed
};

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

module.exports = User;
