const mongoose = require('mongoose');

const compensationSchema = new mongoose.Schema({
    compensationId: {
        type: String,
        unique: true
    },
    ticket: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Ticket',
        required: true
    },
    customer: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    amount: {
        type: Number,
        required: true,
        min: 0
    },
    reason: {
        type: String,
        required: true
    },
    status: {
        type: String,
        default: 'proposed',
        enum: ['proposed', 'approved', 'processed', 'rejected']
    },
    proposedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User', // Super admin who proposed
        required: true
    },
    approvedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User', // Super admin who approved
        default: null
    },
    processedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User', // Super admin who processed payment
        default: null
    },
    proposedAt: {
        type: Date,
        default: Date.now
    },
    approvedAt: {
        type: Date,

    },
    processedAt: {
        type: Date,

    },
    paymentMethod: {
        type: String,
        enum: ['wallet', 'bank_transfer', 'refund'],

    },
    transactionId: {
        type: String,

    },
    notes: {
        type: String,
        default: ''
    }
}, { timestamps: true });

// Pre-save hook to generate compensationId (COMP-001, etc.)
compensationSchema.pre('save', async function (next) {
    if (!this.compensationId) {
        const lastCompensation = await this.constructor.findOne({}, {}, { sort: { 'createdAt': -1 } });
        let nextNumber = 1;
        if (lastCompensation && lastCompensation.compensationId) {
            const lastNumber = parseInt(lastCompensation.compensationId.split('-')[1]);
            if (!isNaN(lastNumber)) {
                nextNumber = lastNumber + 1;
            }
        }
        this.compensationId = `COMP-${nextNumber.toString().padStart(3, '0')}`;
    }
    next();
});

module.exports = mongoose.model('Compensation', compensationSchema);