const mongoose = require('mongoose');

const salarySchema = new mongoose.Schema(
  {
    employee: { type: mongoose.Schema.Types.ObjectId, ref: 'Employee', required: true },
    grossSalary: { type: Number, required: true, min: 0 },
    totalDeduction: { type: Number, required: true, min: 0 },
    netSalary: { type: Number, required: true },
    monthOfPayment: { type: String, required: true, trim: true },
    paymentDate: { type: Date, required: true }
  },
  { timestamps: true }
);

// Ensure netSalary cannot be manually inconsistent.
// Controller should compute it, but this guard helps.
salarySchema.pre('validate', function (next) {
  if (this.grossSalary == null || this.totalDeduction == null) {
    return next();
  }
  this.netSalary = this.grossSalary - this.totalDeduction;
  next();
});

module.exports = mongoose.model('Salary', salarySchema);

