const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');

const stockMovementSchema = new mongoose.Schema({
  product_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Item',
    required: true,
    index: true
  },
  product_name: {
    type: String,
    required: true
  },
  sku: {
    type: String,
    required: true
  },
  type: {
    type: String,
    enum: ['in', 'out', 'adjustment', 'return'],
    required: true
  },
  quantity: {
    type: Number,
    required: true,
    min: 0
  },
  previous_quantity: {
    type: Number,
    required: true,
    min: 0
  },
  new_quantity: {
    type: Number,
    required: true,
    min: 0
  },
  reference: {
    type: String,
    required: true,
    default: 'manual',
    enum: ['purchase', 'sale', 'return', 'adjustment', 'manual', 'other']
  },
  notes: {
    type: String,
    trim: true
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: { 
    createdAt: 'created_at',
    updatedAt: 'updated_at' 
  },
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Add pagination plugin
stockMovementSchema.plugin(mongoosePaginate);

// Indexes for better query performance
stockMovementSchema.index({ product_id: 1, created_at: -1 });
stockMovementSchema.index({ type: 1, created_at: -1 });
stockMovementSchema.index({ user: 1, created_at: -1 });

// Virtual for user details
stockMovementSchema.virtual('user_details', {
  ref: 'User',
  localField: 'user',
  foreignField: '_id',
  justOne: true
});

// Virtual for product details
stockMovementSchema.virtual('product_details', {
  ref: 'Item',
  localField: 'product_id',
  foreignField: '_id',
  justOne: true
});

const StockMovement = mongoose.model('StockMovement', stockMovementSchema);

module.exports = StockMovement;
