const mongoose = require("mongoose");

const attendanceSchema = new mongoose.Schema(
    {
        //  Core Identity
        user: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
            required: true,
        },

        date: {
            type: String, // YYYY-MM-DD (important for querying)
            required: true,
        },

        //  Shift Info
        shift: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Shift",
            // required: true,
        },

        // Time Details
        checkIn: {
            type: String, // "09:00 AM"
            default: null,
        },

        checkOut: {
            type: String, // "06:00 PM"
            default: null,
        },

        totalMinutes: {
            type: Number,
            default: 0,
        },

        overtimeMinutes: {
            type: Number,
            default: 0,
        },

        // Attendance Status
        status: {
            type: String,
            enum: ["Absent", "Present", "Half-Day","Late", "Leave"],
            default: "Absent", // ✅ DEFAULT
        },

        //  Source & Audit
        source: {
            type: String,
            enum: ["manual", "biometric", "mobile"],
            default: "manual",
        },

        markedBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User", // Admin / Manager
            default: null,
        },

        //  Organization Scope
        orgId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Organization",
            required: true,
        },

        //  Soft Delete
        isDeleted: {
            type: Boolean,
            default: false,
        },
        isLocked: {
            type: Boolean,
            default: false,
        },

        //  AUDIT FIELDS (CRITICAL)
        createdBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User", // who first marked attendance
            default: null,
        },

        updatedBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User", // who last edited attendance
            default: null,
        },
    },
    {
        timestamps: true, // createdAt, updatedAt
    }
);


//  CRITICAL INDEX
// One user can have ONLY ONE attendance per date
attendanceSchema.index(
    { user: 1, date: 1 },
    { unique: true }
);

attendanceSchema.index({ orgId: 1, date: 1 });

module.exports = mongoose.model("Attendance", attendanceSchema);
