const mongoose = require('mongoose');

const stockStatusSchema = new mongoose.Schema({
  productId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product',
    required: true,
    unique: true,
  },
  availableQuantity: {
    type: Number,
    required: true,
    min: 0,
  },
  soldQuantity: {
    type: Number,
    default: 0,
    min: 0,
  },
  remainingQuantity: {
    type: Number,
    default: 0,
    min: 0,
  },
  updatedAt: {
    type: Date,
    default: Date.now,
  },
});

stockStatusSchema.pre('save', function (next) {
  this.remainingQuantity = this.availableQuantity - this.soldQuantity;
  this.updatedAt = new Date();
  next();
});

module.exports = mongoose.model('StockStatus', stockStatusSchema);
