import mongoose from "mongoose";

const attendanceSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
      index: true,
    },
    day: { type: String, required: true, index: true }, // YYYY-MM-DD
    checkInAt: { type: Date },
    checkOutAt: { type: Date },
    checkInImageUrl: { type: String, trim: true },
    checkOutImageUrl: { type: String, trim: true },
    note: { type: String, trim: true },
    // Enhanced fields for approval workflow
    status: {
      type: String,
      enum: ["pending", "approved", "rejected"],
      default: "pending",
      index: true,
    },
    approvedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    approvalNote: { type: String, trim: true },
    approvedAt: { type: Date },
    // Location tracking
    checkInLocation: {
      latitude: { type: Number },
      longitude: { type: Number },
      address: { type: String },
    },
    checkOutLocation: {
      latitude: { type: Number },
      longitude: { type: Number },
      address: { type: String },
    },
    // Work summary
    workSummary: { type: String, trim: true },
    totalHours: { type: Number }, // calculated field
    isLate: { type: Boolean, default: false },
    lateByMinutes: { type: Number, default: 0 },
  },
  { timestamps: true }
);

attendanceSchema.index({ userId: 1, day: 1 }, { unique: true });
attendanceSchema.index({ status: 1, day: 1 });

// Calculate total hours before saving
attendanceSchema.pre("save", function (next) {
  if (this.checkInAt && this.checkOutAt) {
    const diff = this.checkOutAt - this.checkInAt;
    this.totalHours = Math.round((diff / (1000 * 60 * 60)) * 100) / 100;
  }
  next();
});

export const Attendance = mongoose.model("Attendance", attendanceSchema);
