const mongoose = require("mongoose");

const discountSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: [true, "Discount name is required"],
            trim: true,
            maxlength: [50, "Discount name cannot exceed 50 characters"],
            index: true,
        },

        code: {
            type: String,
            trim: true,
            uppercase: true,
            unique: true,
            sparse: true, // allows null but unique when present
            maxlength: 20,
        },

        type: {
            type: String,
            enum: ["PERCENTAGE", "FLAT"],
            required: true,
        },

        value: {
            type: Number,
            required: true,
            min: [0, "Discount value cannot be negative"],
        },

        maxDiscountAmount: {
            type: Number,
            min: 0,
            default: null, // used for % discounts
        },

        minOrderAmount: {
            type: Number,
            min: 0,
            default: 0,
        },
        appliesTo: {
            type: String,
            enum: ["INVOICE", "SERVICE", "TASK"],
            default: "INVOICE",
        },

        isStackable: {
            type: Boolean,
            default: false, // multiple discounts allowed?
        },

        validFrom: {
            type: Date,
            default: Date.now,
        },
        validTill: {
            type: Date,
            default: null,
        },
        isActive: {
            type: Boolean,
            default: true,
            index: true,
        },

        isDefault: {
            type: Boolean,
            default: false,
        },
        orgId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Organization",
            required: true,
            index: true,
        },
        createdBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
            required: true,
        },
        updatedBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
            default: null,
        },
        isDeleted: {
            type: Boolean,
            default: false,
            index: true,
        },
    },
    {
        timestamps: true,
    }
);

discountSchema.pre("save", function (next) {
    // Percentage rules
    if (this.type === "PERCENTAGE" && this.value > 100) {
        return next(new Error("Percentage discount cannot exceed 100%"));
    }
    // Flat discount sanity
    if (this.type === "FLAT" && this.value <= 0) {
        return next(new Error("Flat discount must be greater than zero"));
    }
    // Validity check
    if (this.validTill && this.validTill < this.validFrom) {
        return next(new Error("validTill cannot be before validFrom"));
    }

    next();
});

discountSchema.index({ orgId: 1, name: 1 }, { unique: true });

module.exports = mongoose.model("Discount", discountSchema);
