const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MonthlyExpenseSchema = new Schema({
  companyId: {
    type: Schema.Types.ObjectId,
    ref: 'Company',  // Reference to the Company model
    required: true
  },
  branchId: {
    type: Schema.Types.ObjectId,
    ref: 'Branch',  // Reference to the Branch model
    required: true
  },
 
  rent: {
    type: Number,   // Rent expenses
    default: 0
  },
  salaries: {
    type: Number,   // Salaries and wages for employees
    default: 0
  },
  utilities: {
    type: Number,   // Utilities such as electricity, water, etc.
    default: 0
  },
  tax: {
    type: Number,   // 
    default: 0
  },

  otherExpenses: {
    type: Number,   // Any other miscellaneous expenses
    default: 0
  },
  totalExpense: {
    type: Number,   // Automatically calculated total for the month's expenses
    default: 0
  }
}, {
  timestamps: true  // Adds createdAt and updatedAt fields
});

// Pre-save middleware to calculate total expense
MonthlyExpenseSchema.pre('save', function(next) {
  this.totalExpense = this.rent + this.salaries + this.utilities + this.otherExpenses;
  next();
});

module.exports = mongoose.model('MonthlyExpense', MonthlyExpenseSchema);
