const mongoose = require('mongoose');

const otpSchema = new mongoose.Schema({
  phone: {
    type: String,
    required: [true, 'Phone number is required'],
    trim: true
  },
  otp: {
    type: String,
    required: [true, 'OTP is required']
  },
  expiresAt: {
    type: Date,
    default: Date.now,
    expires: 300 // 5 minutes in seconds
  },
  verified: {
    type: Boolean,
    default: false
  }
}, {
  timestamps: true
});

// Generate OTP
const generateOtp = () => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// Method to check if OTP is expired
otpSchema.methods.isExpired = function() {
  return this.expiresAt < new Date();
};

// Static method to create a new OTP
otpSchema.statics.createOtp = async function(phone) {
  const otp = generateOtp();
  const expiresAt = new Date(Date.now() + 5 * 60 * 1000); // 5 minutes from now
  
  // Remove any existing OTPs for this phone
  await this.deleteMany({ phone });
  
  // Create new OTP
  return this.create({
    phone,
    otp,
    expiresAt,
    verified: false
  });
};

const Otp = mongoose.model('Otp', otpSchema);

module.exports = Otp;
