const mongoose = require('mongoose');

const withdrawalRequestSchema = new mongoose.Schema({
    requestId: {
        type: String,
        unique: true
    },
    requester: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        refPath: 'requesterType'
    },
    requesterType: {
        type: String,
        required: true,
        enum: ['Vendor', 'ZoneAdmin']
    },
    amount: {
        type: Number,
        required: true,
        min: 1
    },
    status: {
        type: String,
        default: 'pending',
        enum: ['pending', 'approved', 'rejected', 'processed']
    },
    // Bank details snapshot at time of request
    bankDetails: {
        accountHolderName: String,
        accountNumber: String,
        ifscCode: String,
        bankName: String,
        upiId: String
    },
    // Payment proof after processing
    paymentProof: {
        type: String, // Image URL or Transaction ID
        default: null
    },
    paymentMethod: {
        type: String,
        enum: ['bank_transfer', 'upi', 'cheque'],
        default: null
    },
    paymentTransactionId: {
        type: String,
        default: null
    },
    // Timestamps
    requestedAt: {
        type: Date,
        default: Date.now
    },
    approvedAt: {
        type: Date,
        default: null
    },
    processedAt: {
        type: Date,
        default: null
    },
    rejectedAt: {
        type: Date,
        default: null
    },
    // Admin references
    approvedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        default: null
    },
    processedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        default: null
    },
    rejectedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        default: null
    },
    rejectionReason: {
        type: String,
        default: null
    },
    notes: {
        type: String,
        default: ''
    }
}, { timestamps: true });

// Pre-save hook to generate requestId
withdrawalRequestSchema.pre('save', async function (next) {
    if (!this.requestId) {
        const prefix = this.requesterType === 'Vendor' ? 'WDV' : 'WDZ';
        const lastRequest = await this.constructor.findOne(
            { requesterType: this.requesterType },
            {},
            { sort: { 'createdAt': -1 } }
        );
        let nextNumber = 1;
        if (lastRequest && lastRequest.requestId) {
            const lastNumber = parseInt(lastRequest.requestId.split('-')[1]);
            if (!isNaN(lastNumber)) {
                nextNumber = lastNumber + 1;
            }
        }
        this.requestId = `${prefix}-${nextNumber.toString().padStart(4, '0')}`;
    }
    next();
});

// Index for efficient queries
withdrawalRequestSchema.index({ requester: 1, requesterType: 1 });
withdrawalRequestSchema.index({ status: 1 });

module.exports = mongoose.model('WithdrawalRequest', withdrawalRequestSchema);