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

export type MovementType = 'ENTRY' | 'ADJUSTMENT' | 'CONSUMPTION';

export interface IStockMovement extends Document {
    organizationId?: string;
    createdBy?: string;
    stockItemId: mongoose.Types.ObjectId;
    movementNumber?: number;
    type: MovementType;
    quantity: number; // Positive for entry, negative for exit
    date: Date;
    responsible: string; // User who performed the action
    reason?: string; // For ADJUSTMENT
    requester?: string; // For CONSUMPTION
    notes?: string;
    createdAt: Date;
}

const StockMovementSchema: Schema = new Schema({
    organizationId: { type: String, index: true },
    createdBy: { type: String, index: true },
    stockItemId: { type: Schema.Types.ObjectId, ref: 'StockItem', required: true },
    movementNumber: { type: Number },
    type: { type: String, enum: ['ENTRY', 'ADJUSTMENT', 'CONSUMPTION'], required: true },
    quantity: { type: Number, required: true },
    date: { type: Date, default: Date.now },
    responsible: { type: String, required: true },
    reason: { type: String },
    requester: { type: String },
    notes: { type: String }
}, { timestamps: true });

export default mongoose.models.StockMovement || mongoose.model<IStockMovement>('StockMovement', StockMovementSchema);
