import bcrypt from "bcryptjs";
import mongoose from "mongoose";

const addressSchema = new mongoose.Schema({
  label: String,
  line1: String,
  city: String,
  state: String,
  phone: String,
  isDefault: Boolean
});

const userSchema = new mongoose.Schema(
  {
    fullName: { type: String, required: true },
    email: { type: String, required: true, unique: true, lowercase: true, index: true },
    phone: String,
    password: { type: String, required: true, select: false },
    role: { type: String, enum: ["customer", "seller", "dispatch", "accountant", "admin", "super_admin"], default: "customer" },
    isVerified: { type: Boolean, default: false },
    walletBalance: { type: Number, default: 0 },
    loyaltyPoints: { type: Number, default: 0 },
    addresses: [addressSchema],
    permissions: [String]
  },
  { timestamps: true }
);

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

userSchema.methods.comparePassword = function comparePassword(password) {
  return bcrypt.compare(password, this.password);
};

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