const mongoose = require("mongoose");

const employeePayrollHistorySchema = new mongoose.Schema(
  {
  
    orgId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Organization",
      required: true,
      index: true,
    },

    employeeId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User", // 
      required: true,
      index: true,
    },

    payrollId: {
      type: String,
      required: true,
      index: true,
    },

    payrollMonth: {
      type: Number, // 1–12
      required: true,
      index: true,
    },

    payrollYear: {
      type: Number, // 2025
      required: true,
      index: true,
    },

    /* ================= SALARY SNAPSHOT ================= */
    salaryBreakup: {
      earnings: [
        {
          name: String,
          amount: Number,
        },
      ],
      deductions: [
        {
          name: String,
          amount: Number,
        },
      ],
      gross: { type: Number, required: true },
      netPay: { type: Number, required: true },
    },

    /* ================= ATTENDANCE SUMMARY ================= */
    attendanceSummary: {
      totalDays: Number,
      presentDays: Number,
      absentDays: Number,
      halfDays: Number,
      leaveDays: Number,
    },

    /* ================= DAILY ATTENDANCE SNAPSHOT ================= */
    attendanceDetails: [
      {
        date: { type: Date, required: true },
        status: {
          type: String,
          enum: ["Present", "Absent", "Half-Day", "Leave"],
          required: true,
        },
        workedHours: Number,
      },
    ],

    /* ================= METADATA ================= */
    generatedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },

    generatedAt: {
      type: Date,
      default: Date.now,
    },
  },
  { timestamps: true }
);

/* ================= INDEXES ================= */

// One payroll snapshot per employee per month
employeePayrollHistorySchema.index(
  { orgId: 1, employeeId: 1, payrollMonth: 1, payrollYear: 1 },
  { unique: true }
);
// Fast lookup by payroll
employeePayrollHistorySchema.index({ payrollId: 1 });

module.exports = mongoose.model(
  "PayrollHistory",
  employeePayrollHistorySchema
);
