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 territorymanagerSchema = new mongoose.Schema(
  {
    designation: {
      type: String,
      required: true,
      default: "Territory Manager",
    },
    name: {
      type: String,
      required: true,
    },
    mobileNumber: {
      type: String,
      required: true,
      unique: true,
    },
    otp: {
      type: String,
      required: false,
    },
    otpExpires: {
      type: Date,
    },
    isVerified: {
      type: Boolean,
      default: false,
    },
    email: {
      type: String,
      required: false,
      unique: true,
      validate: [validator.isEmail, "Please enter a valid Email"],
    },
    password: {
      type: String,
      minLength: [6, "Password should be greater than 6 characters"],
      select: false,
    },
    newMobileNumber: { type: String },
    resetPasswordToken: String,
    resetPasswordExpire: Date,
    uniqueId: {
      type: String,
      unique: true,
    },
    fcm_token: {
      type: String,
      default: null,
      sparse: true,
    },
  },
  { timestamps: true }
);

territorymanagerSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }

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

territorymanagerSchema.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
territorymanagerSchema.methods.getJWTToken = function () {
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET);
};

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

// Generating Reset Token
territorymanagerSchema.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 TerritoryManager = mongoose.model(
  "TerritoryManager",
  territorymanagerSchema
);

export default TerritoryManager;
