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 RetailDistributorSchema = new mongoose.Schema(
  {
    uniqueId: {
      type: String,
      unique: true,
    },
    designation: {
      type: String,
      required: true,
      default: "Retail Distributor",
    },
    name: {
      type: String,
      required: true,
      maxlength: [50, "Name cannot be more than 50 characters"],
    },
    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,
    },
    mobile_number: {
      type: String,
      required: true,
    },
    principal_distributer: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      // required: true,
    },
    addedBy: {
      type: mongoose.Schema.Types.ObjectId,
      refPath: "userType",
      // required: true,
    },
    userType: {
      type: String,
      // required: true,
      enum: ["SalesCoOrdinator", "TerritoryManager"],
    },
    mappedTM: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "TerritoryManager",
    },
    mappedSC: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "SalesCoOrdinator",
    },
    kyc: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "KYC",
    },
    resetPasswordToken: String,
    resetPasswordExpire: Date,
    fcm_token: {
      type: String,
      default: null,
    },
  },
  { timestamps: true }
);

// Pre-save middleware to set 'mappedSC' or 'mappedTM' if not provided, based on 'userType' and 'addedBy'
RetailDistributorSchema.pre("save", function (next) {
  // Only set defaults if the document is new (not yet saved)
  if (this.isNew) {
    if (
      !this.mappedSC &&
      this.userType === "SalesCoOrdinator" &&
      this.addedBy
    ) {
      this.mappedSC = this.addedBy;
    }
    if (
      !this.mappedTM &&
      this.userType === "TerritoryManager" &&
      this.addedBy
    ) {
      this.mappedTM = this.addedBy;
    }
  }
  next();
});
RetailDistributorSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }

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

RetailDistributorSchema.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
RetailDistributorSchema.methods.getJWTToken = function () {
  return jwt.sign({ _id: this._id }, process.env.JWT_SECRET, {
    expiresIn: "1d", // Token will expire in 1 day
  });
};

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

// Generating Reset Token
RetailDistributorSchema.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 RetailDistributor = mongoose.model(
  "RetailDistributor",
  RetailDistributorSchema
);
export default RetailDistributor;
