import mongoose from 'mongoose';

const employeeSchema = new mongoose.Schema(
  {
    employeeId: { type: String, required: true, unique: true },
    firstName: { type: String, required: true, trim: true },
    lastName: { type: String, required: true, trim: true },
    email: { type: String, required: true, unique: true, lowercase: true },
    phone: { type: String, default: '' },
    role: {
      type: String,
      enum: ['teacher', 'admin_staff', 'principal', 'support', 'librarian', 'counselor'],
      default: 'teacher',
    },
    department: { type: mongoose.Schema.Types.ObjectId, ref: 'Department', required: true },
    joinDate: { type: Date, required: true },
    status: { type: String, enum: ['active', 'on_leave', 'terminated'], default: 'active' },
    bankAccount: { type: String, default: '' },
    address: { type: String, default: '' },
    photo: { type: String, default: '' },
    salary: {
      basic: { type: Number, required: true, default: 0 },
      housing: { type: Number, default: 0 },
      transport: { type: Number, default: 0 },
      medical: { type: Number, default: 0 },
      bonus: { type: Number, default: 0 },
    },
    deductions: {
      tax: { type: Number, default: 0 },
      pension: { type: Number, default: 0 },
      insurance: { type: Number, default: 0 },
      loan: { type: Number, default: 0 },
    },
  },
  { timestamps: true }
);

employeeSchema.virtual('fullName').get(function () {
  return `${this.firstName} ${this.lastName}`;
});

employeeSchema.virtual('grossSalary').get(function () {
  const s = this.salary;
  return (s.basic || 0) + (s.housing || 0) + (s.transport || 0) + (s.medical || 0) + (s.bonus || 0);
});

employeeSchema.virtual('totalDeductions').get(function () {
  const d = this.deductions;
  return (d.tax || 0) + (d.pension || 0) + (d.insurance || 0) + (d.loan || 0);
});

employeeSchema.virtual('netSalary').get(function () {
  return this.grossSalary - this.totalDeductions;
});

employeeSchema.set('toJSON', { virtuals: true });
employeeSchema.set('toObject', { virtuals: true });

export default mongoose.model('Employee', employeeSchema);
