const mongoose = require('mongoose');

const transferSchema = new mongoose.Schema({
  companyId: { type: mongoose.Schema.Types.ObjectId, ref: 'Company', required: true },
  fromBranchId: { type: mongoose.Schema.Types.ObjectId, ref: 'Branch', required: true },
  toBranchId: { type: mongoose.Schema.Types.ObjectId, ref: 'Branch', required: true },
  itemId: { type: mongoose.Schema.Types.ObjectId, ref: 'Item', required: true },
  quantity: { type: Number, required: true },
  status: { type: String, default: 'Pending', enum: ['Pending','Returned' ,'Accepted', 'Rejected'] },
  fromBranchBalance: { type: Number },
  toBranchBalance: { type: Number },
  reasonForRejection: { type: String, default: null }, // Optional: Reason if transfer is rejected
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }, // Updated each time the status changes
});

// Middleware to update the `updatedAt` field whenever a document is modified
transferSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

module.exports = mongoose.model('Transfer', transferSchema);
