import mongoose, { Schema, Document } from 'mongoose';

export interface IStockItem extends Document {
    organizationId?: string;
    createdBy?: string;
    dataSheetId: mongoose.Types.ObjectId;
    rrNumber: string; // Registro de Rastreabilidade
    batchNumber: string; // Lote
    color?: string;
    invoiceNumber?: string; // Nota Fiscal
    receivedBy?: string; // Quem recebeu
    quantity: number;
    unit: string;
    minStock?: number; // Estoque mínimo estipulado
    expirationDate?: Date;
    entryDate: Date;
    notes?: string;
    createdAt: Date;
    updatedAt: Date;
}

const StockItemSchema: Schema = new Schema({
    organizationId: { type: String, index: true },
    createdBy: { type: String, index: true },
    dataSheetId: { type: Schema.Types.ObjectId, ref: 'TechnicalDataSheet', required: true },
    rrNumber: { type: String, required: true },
    batchNumber: { type: String, required: true },
    color: { type: String },
    invoiceNumber: { type: String },
    receivedBy: { type: String },
    quantity: { type: Number, required: true, default: 0 },
    unit: { type: String, required: true },
    minStock: { type: Number, default: 0 },
    expirationDate: { type: Date },
    entryDate: { type: Date, default: Date.now },
    notes: { type: String }
}, { timestamps: true });

// Compound index to prevent duplicate RR within an organization, if desirable.
// For now, indexing RR for fast lookup.
StockItemSchema.index({ organizationId: 1, rrNumber: 1 });

export default mongoose.models.StockItem || mongoose.model<IStockItem>('StockItem', StockItemSchema);
