import mongoose from 'mongoose';
import { OrganizerFillStatus } from '@meshitrack/shared';

const organizerDeductionSchema = new mongoose.Schema(
  {
    cabinetItemId: { type: String, required: true },
    quantityTaken: { type: Number, required: true },
  },
  { _id: false },
);

const organizerFillItemSchema = new mongoose.Schema(
  {
    medicineId: { type: String, required: true },
    medicineName: { type: String, required: true },
    quantityNeeded: { type: Number, required: true },
    quantityTaken: { type: Number, required: true },
    wasShort: { type: Boolean, required: true },
    shortage: { type: Number, required: true },
    deductions: { type: [organizerDeductionSchema], required: true },
  },
  { _id: false },
);

const organizerFillSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    userId: { type: String, required: true },
    regimenId: { type: String, required: true },
    regimenName: { type: String, required: true },
    numberOfDays: { type: Number, required: true },
    fillDate: { type: Date, required: true },
    items: { type: [organizerFillItemSchema], required: true },
    status: {
      type: String,
      enum: Object.values(OrganizerFillStatus),
      required: true,
    },
    notes: { type: String },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

organizerFillSchema.index({ householdId: 1, userId: 1, fillDate: -1 });
organizerFillSchema.index({ householdId: 1, regimenId: 1, fillDate: -1 });
organizerFillSchema.index({ householdId: 1, status: 1 });

export const OrganizerFillModel = mongoose.model('OrganizerFill', organizerFillSchema);
export type OrganizerFillDocument = mongoose.InferSchemaType<typeof organizerFillSchema> & {
  _id: mongoose.Types.ObjectId;
};
