const mongoose = require('mongoose');

const salesSchema = new mongoose.Schema({
  productId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product',
    required: [true, 'Product reference is required'],
  },
  soldQuantity: {
    type: Number,
    required: [true, 'Sold quantity is required'],
    min: [1, 'Sold quantity must be at least 1'],
  },
  soldUnitPrice: {
    type: Number,
    required: [true, 'Sold unit price is required'],
    min: [0, 'Sold unit price cannot be negative'],
  },
  soldTotalPrice: {
    type: Number,
  },
  salesDate: {
    type: Date,
    required: [true, 'Sales date is required'],
    default: Date.now,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    type: Date,
    default: Date.now,
  },
});

// Auto-calculate soldTotalPrice
salesSchema.pre('save', function (next) {
  this.soldTotalPrice = this.soldQuantity * this.soldUnitPrice;
  this.updatedAt = new Date();
  next();
});

salesSchema.pre('findOneAndUpdate', function (next) {
  const update = this.getUpdate();
  if (update.soldQuantity !== undefined && update.soldUnitPrice !== undefined) {
    update.soldTotalPrice = update.soldQuantity * update.soldUnitPrice;
  }
  update.updatedAt = new Date();
  next();
});

module.exports = mongoose.model('Sales', salesSchema);
