import mongoose from 'mongoose';
import { DosageUnit } from '@meshitrack/shared';
import { RefillListStatus } from '@meshitrack/shared';

const refillListItemSchema = new mongoose.Schema(
  {
    medicineId: { type: String, required: true },
    medicineName: { type: String, required: true },
    quantity: { type: Number, required: true, min: 0 },
    unit: { type: String, enum: Object.values(DosageUnit), required: true },
    estimatedPrice: { type: Number, min: 0 },
    actualPrice: { type: Number, min: 0 },
    checked: { type: Boolean, required: true, default: false },
    checkedAt: { type: Date },
    addedToCabinet: { type: Boolean, required: true, default: false },
    storeId: { type: String },
    notes: { type: String },
  },
  { _id: true },
);

const refillListSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    name: { type: String, required: true },
    items: { type: [refillListItemSchema], required: true, default: [] },
    status: {
      type: String,
      enum: Object.values(RefillListStatus),
      required: true,
      default: RefillListStatus.ACTIVE,
    },
    preferredStoreId: { type: String },
    totalEstimatedCost: { type: Number },
    createdBy: { type: String, required: true },
  },
  { timestamps: true },
);

refillListSchema.index({ householdId: 1, status: 1 });
refillListSchema.index({ householdId: 1, createdAt: -1 });

export const RefillListModel = mongoose.model('RefillList', refillListSchema);
export type RefillListDocument = mongoose.InferSchemaType<typeof refillListSchema> & {
  _id: mongoose.Types.ObjectId;
};
