const mongoose = require("mongoose");

const otpVerificationSchema = new mongoose.Schema(
    {
        identifier: {
            type: String, // Email or Phone Number
            required: true,
            trim: true,
            lowercase: true, // Useful for emails, harmless for phone numbers usually
        },
        type: {
            type: String,
            enum: ['email', 'phone'],
            required: true,
            default: 'email'
        },
        user: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
        otpHash: {
            type: String,
            required: true,
        },
        expiresAt: {
            type: Date,
            required: true,
            index: { expires: 0 },
        },
        attempts: {
            type: Number,
            default: 0,
        },
        sendCount: {
            type: Number,
            default: 0,
        },
        windowStart: {
            type: Date,
            default: Date.now,
        },
        cooldownUntil: {
            type: Date,
        },
        lastSentAt: {
            type: Date,
        },
        verified: {
            type: Boolean,
            default: false,
        },
    },
    { timestamps: true }
);

// Compound index to ensure uniqueness per identifier and type
otpVerificationSchema.index({ identifier: 1, type: 1 }, { unique: true });

const OtpVerification = mongoose.model(
    "OtpVerification",
    otpVerificationSchema
);

module.exports = OtpVerification;
