import dotenv from "dotenv";
dotenv.config();
import mongoose from "mongoose";
import validator from "validator";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import crypto from "crypto";

const userSchema = new mongoose.Schema(
  {
    uniqueId: {
      type: String,
      unique: true,
      validate: {
        validator: function (value) {
          // Only require uniqueId if the role is not "admin"
          if (this.role !== "admin" && !value) {
            return false;
          }
          return true;
        },
        message: "Unique ID is required for users",
      },
    },
    SBU: {
      type: String,
      validate: {
        validator: function (value) {
          // Only require SBU if the role is not "admin"
          if (this.role !== "admin" && !value) {
            return false;
          }
          return true;
        },
        message: "SBU is required for users",
      },
    },
    name: {
      type: String,
      required: [true, "Please Enter Your Name"],
      maxLength: [30, "Name cannot exceed 30 characters"],
    },
    email: {
      type: String,
      required: [true, "Please Enter Your Email"],
      unique: true,
      validate: [validator.isEmail, "Please Enter a valid Email"],
    },
    phone: {
      type: String,
      required: [true, "Please Enter Your phone no."],
      validate: {
        validator: function (v) {
          return /^\d{10}$/.test(v);
        },
        message: "Please enter a valid 10-digit phone number",
      },
    },
    password: {
      type: String,
      required: [true, "Please Enter Your Password"],
      minLength: [6, "Password should be greater than 6 characters"],
      select: false,
    },
    avatar: {
      public_id: {
        type: String,
        default: "",
      },
      url: {
        type: String,
        default: "",
      },
    },
    role: {
      type: String,
      default: "user",
    },
    mappedby: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "TerritoryManager",
    },
    mappedbySC: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "SalesCoOrdinator",
    },
    accessTo: {},
    resetPasswordToken: String,
    resetPasswordExpire: Date,
    fcm_token: {
      type: String,
      default: null,
    },
  },
  { timestamps: true }
);

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }
  this.password = await bcrypt.hash(this.password, 10);
});

// Generate uniqueId before saving
userSchema.pre("save", function (next) {
  if (!this.uniqueId) {
    const currentYear = new Date().getFullYear().toString().slice(-2);
    const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
    this.uniqueId = `${currentYear}-${randomChars}`;
  }
  next();
});

// JWT TOKEN
userSchema.methods.getJWTToken = function () {
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_TIME,
  });
};

// Compare Password
userSchema.methods.comparePassword = async function (password) {
  return await bcrypt.compare(password, this.password);
};

// Generating Reset Token
userSchema.methods.getResetPasswordToken = function () {
  const resetToken = crypto.randomBytes(20).toString("hex");
  this.resetPasswordToken = crypto
    .createHash("sha256")
    .update(resetToken)
    .digest("hex");
  this.resetPasswordExpire = Date.now() + 15 * 60 * 1000; // 15 minutes
  return resetToken;
};

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