const mongoose = require('mongoose');
const bcrypt = require('bcryptjs')
const jwt = require("jsonwebtoken");

const userSchema = new mongoose.Schema({
  userName: {
    type: String,
    unique: true,
    required: true,
    trim: true,
    lowercase: true,
    index: true
  },
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true,
    lowercase: true,
    index: true
  },
  phone: {
    type: String,
    minlength: 10,
    maxlength: 15
  },
  fullName: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    minlength: 6,
    select: false
  },
  // Social Login Fields
  googleId: {
    type: String,
    sparse: true,
    index: true
  },
  facebookId: {
    type: String,
    sparse: true,
    index: true
  },
  authProvider: {
    type: String,
    enum: ['local', 'google', 'facebook'],
    default: 'local'
  },
  isProfileComplete: {
    type: Boolean,
    default: true
  },
  profileImageUrl: {
    type: String,
  },
  role: {
    type: String,
    // enum: ['user', 'super-admin', 'zone-admin', 'vendor', 'driver'],
    default: 'user'
  },
  plan: {
    type: String,
    enum: ['free', 'premium'],
    default: 'free'
  },
  refreshToken: {
    type: [String],
  },
  resetToken: {
    type: String,
  },
  resetTokenExpiry: {
    type: Date,
  },
  status: {
    type: String,
    enum: ['active', 'suspended'],
    default: 'active',
    index: true
  },
  walletBalance: {
    type: Number,
    default: 0
  },
  totalTrips: {
    type: Number,
    default: 0
  },
  lastActiveAt: {
    type: Date,
    default: Date.now
  },
  preferredLanguage: {
    type: String,
    enum: ['en', 'hi', 'fr', 'de', 'ar', 'es'],
    default: 'en'
  },
  gender: {
    type: String,
    enum: ['MALE', 'FEMALE', 'OTHER'],
  },
  dob: {
    type: Date,
  },
  nationality: {
    type: String,
  },
  maritalStatus: {
    type: String,
    enum: ['Single', 'Married'],
  },
  anniversaryDate: {
    type: Date,
  },
  fullAddress: {
    address: {
      type: String,
      trim: true
    },
    city: {
      type: String,
      trim: true
    },
    state: {
      type: String,
      trim: true
    },
    pincode: {
      type: String,
      trim: true,
      minlength: 6,
      maxlength: 6
    }
  }
}, { timestamps: true });

userSchema.pre("save", function () {
  if (!this.isModified("password")) {
    return;
  }
  let salt = bcrypt.genSaltSync(10);
  this.password = bcrypt.hashSync(this.password, salt);
});

userSchema.methods.comparepassword = function (password) {
  if (!this.password) return false;
  return bcrypt.compareSync(password, this.password);
};

userSchema.methods.generateAccessToken = function () {
  const { getEnv } = require("../utils/envLoader");
  const token = jwt.sign({
    _id: this._id,
    email: this.email,
    userName: this.userName,
    fullName: this.fullName,
    role: this.role,
    plan: this.plan
  }, getEnv("JWT_SECRET") || process.env.JWT_SECRET,
    { expiresIn: getEnv("JWT_EXPIRES_IN") || process.env.JWT_EXPIRES_IN });
  return token;
}

userSchema.methods.generateRefreshToken = function () {
  const { getEnv } = require("../utils/envLoader");
  const refreshToken = jwt.sign(
    { _id: this._id, role: this.role },
    getEnv("REFRESHTOKEN_SECRET") || process.env.REFRESHTOKEN_SECRET,
    { expiresIn: getEnv("REFRESH_TOKEN_EXPIRES_IN") || process.env.REFRESH_TOKEN_EXPIRES_IN }
  );
  return refreshToken;
}

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

module.exports = User;
