const mongoose = require('mongoose');

const couponSchema = new mongoose.Schema({
    code: {
        type: String,
        required: [true, 'Coupon code is required'],
        unique: true,
        uppercase: true,
        trim: true
    },
    discountType: {
        type: String,
        required: true,
        enum: ['percentage', 'fixed'],
        default: 'percentage'
    },
    discountValue: {
        type: Number,
        required: [true, 'Discount value is required'],
        min: [0, 'Discount value must be positive']
    },
    minOrderValue: {
        type: Number,
        default: 0,
        min: [0, 'Minimum order value must be positive']
    },
    maxDiscount: {
        type: Number,
        default: null // Only for percentage discounts
    },
    expiryDate: {
        type: Date,
        required: [true, 'Expiry date is required']
    },
    usageLimit: {
        type: Number,
        default: null // null means unlimited
    },
    usedCount: {
        type: Number,
        default: 0
    },
    isActive: {
        type: Boolean,
        default: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// Method to check if coupon is valid
couponSchema.methods.isValid = function(orderTotal) {
    const now = new Date();
    
    // Check if coupon is active
    if (!this.isActive) {
        return { valid: false, message: 'Coupon is not active' };
    }
    
    // Check if expired
    if (this.expiryDate < now) {
        return { valid: false, message: 'Coupon has expired' };
    }
    
    // Check usage limit
    if (this.usageLimit && this.usedCount >= this.usageLimit) {
        return { valid: false, message: 'Coupon usage limit reached' };
    }
    
    // Check minimum order value
    if (orderTotal < this.minOrderValue) {
        return { valid: false, message: `Minimum order value must be $${this.minOrderValue}` };
    }
    
    return { valid: true };
};

// Method to calculate discount
couponSchema.methods.calculateDiscount = function(orderTotal) {
    if (this.discountType === 'percentage') {
        let discount = (orderTotal * this.discountValue) / 100;
        if (this.maxDiscount && discount > this.maxDiscount) {
            discount = this.maxDiscount;
        }
        return Math.floor(discount);
    } else {
        return this.discountValue;
    }
};

module.exports = mongoose.model('Coupon', couponSchema);
