import mongoose, { Schema } from "mongoose";

const invoiceSchema = new Schema({
    customId: String,
    products:[{name:String,quantity:Number,price:Number,
    inventoryId:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Inventory',
        required: true,
    }
    }],
    discountType: {type:String,enum:['Flat','Percentage'],default:null},
    discountValue: Number,
    subTotal: Number,
    finalAmount: Number,
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true,
    },
    serviceId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Service',
        required: true,
    }
}, { timestamps: true })
invoiceSchema.pre('save', async function () {
    if (!this.customId) {
        let isUnique = false;
        let newId;

        while (!isUnique) {
            newId = Math.floor(100000 + Math.random() * 900000).toString(); // ✅ 6-digit

            const existing = await this.constructor.findOne({ customId: newId });
            if (!existing) {
                isUnique = true;
            }
        }

        this.customId = newId;
    }
});
const Invoice = mongoose.model('Invoice', invoiceSchema);
export default Invoice;