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

export interface IStockAuditLog extends Document {
    organizationId?: string;
    stockItemId: mongoose.Types.ObjectId;
    movementId?: mongoose.Types.ObjectId; // Optional, might be deleted
    movementNumber?: number;
    userId: string;
    userName: string;
    action: 'CREATE' | 'UPDATE' | 'DELETE';
    details: string; // Human readable summary
    oldValues?: Record<string, any>;
    newValues?: Record<string, any>;
    timestamp: Date;
}

const StockAuditLogSchema: Schema = new Schema({
    organizationId: { type: String, index: true },
    stockItemId: { type: Schema.Types.ObjectId, ref: 'StockItem', required: true },
    movementId: { type: Schema.Types.ObjectId, ref: 'StockMovement' },
    movementNumber: { type: Number },
    userId: { type: String, required: true },
    userName: { type: String, required: true },
    action: { type: String, required: true, enum: ['CREATE', 'UPDATE', 'DELETE'] },
    details: { type: String, required: true },
    oldValues: { type: Object },
    newValues: { type: Object },
    timestamp: { type: Date, default: Date.now }
}, { timestamps: true });

export default mongoose.models.StockAuditLog || mongoose.model<IStockAuditLog>('StockAuditLog', StockAuditLogSchema);
