import mongoose from 'mongoose';

const shiftSchema = new mongoose.Schema(
  {
    shiftNumber: { type: String, required: true, unique: true },
    register: { type: String, required: true, trim: true, maxlength: 60 },
    cashier: {
      id: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin', required: true },
      name: { type: String, default: '' },
    },
    status: {
      type: String,
      enum: ['OPEN', 'CLOSED'],
      default: 'OPEN',
      index: true,
    },
    openingCash: { type: Number, required: true, min: 0 },
    openingNote: { type: String, default: '', trim: true, maxlength: 300 },
    openedAt: { type: Date, default: Date.now, index: true },
    closedAt: { type: Date, default: null },
    closing: {
      expectedCash: { type: Number, default: 0 },
      actualCash: { type: Number, default: null },
      difference: { type: Number, default: 0 },
      note: { type: String, default: '', trim: true, maxlength: 500 },
    },
    totals: {
      cashSales: { type: Number, default: 0 },
      upiSales: { type: Number, default: 0 },
      cardSales: { type: Number, default: 0 },
      totalSales: { type: Number, default: 0 },
      saleCount: { type: Number, default: 0 },
      cashRefunds: { type: Number, default: 0 },
      upiRefunds: { type: Number, default: 0 },
      cardRefunds: { type: Number, default: 0 },
      totalRefunds: { type: Number, default: 0 },
      refundCount: { type: Number, default: 0 },
      cashIn: { type: Number, default: 0 },
      cashOut: { type: Number, default: 0 },
      expectedCash: { type: Number, default: 0 },
    },
  },
  { timestamps: true }
);

shiftSchema.index({ register: 1, status: 1 });
shiftSchema.index({ 'cashier.id': 1, status: 1 });

export default mongoose.model('Shift', shiftSchema);
