
import mongoose, { CallbackError, Document, Schema } from 'mongoose';

export interface IUser extends Document {
  _id: mongoose.Types.ObjectId;
  name: string;
  email: string;
  password: string;
  phone?: string;
  username?: string;
  bio?: string;
  avatar?: string;
  role: mongoose.Types.ObjectId;
  status: 'active' | 'inactive';
  passwordChangedAt: Date;
  createdAt: Date;
  updatedAt: Date;
}

const UserSchema = new Schema<IUser>(
  {
    name: {
      type: String,
      required: [true, 'Name is required'],
      trim: true,
      maxlength: [200, 'Vame cannot exceed 100 characters']
    },

    email: {
      type: String,
      required: [true, 'Email is required'],
      unique: true,
      lowercase: true,
      trim: true,
      match: [/^\S+@\S+\.\S+$/, 'Please use a valid email address']
    },

    password: {
      type: String,
      required: [true, 'Password is required'],
      minlength: [6, 'Password must be at least 6 characters long'],
      // select: false
    },

    phone: {
      type: String,
      trim: true,
    },

    username: {
      type: String,
      trim: true,
      unique: true,
      sparse: true,  // Allows multiple null values
      maxlength: [50, 'Username cannot exceed 50 characters']
    },

    bio: {
      type: String,
      trim: true,
      maxlength: [500, 'Bio cannot exceed 500 characters']
    },

    avatar: {
      type: String,
      trim: true,
    },

    role: {
      type: Schema.Types.ObjectId,
      ref: 'UserType',
      required: [true, 'User role is required']
    },

    status: {
      type: String,
      enum: ['active', 'inactive'],
      default: 'active'
    },
    passwordChangedAt: {
      type: Date,
      default: null
    }
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
  }
)

// Indexes
UserSchema.index({ email: 1 }, { unique: true });
UserSchema.index({ username: 1 }, { sparse: true });
UserSchema.index({ role: 1 });

// Auto-update passwordChangedAt whenever password changes
UserSchema.pre<IUser>('save', function() {
  if (!this.isModified('password') || this.isNew) return;
  this.passwordChangedAt = new Date();
});

export default mongoose.models.User ||
  mongoose.model<IUser>('User', UserSchema);