import mongoose from 'mongoose';
import { CabinetEventType, CabinetEventSourceType } from '@meshitrack/shared';

const cabinetEventSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    userId: { type: String, required: true },
    cabinetItemId: { type: String, required: true },
    medicineId: { type: String, required: true },
    medicineName: { type: String, required: true },
    eventType: { type: String, enum: Object.values(CabinetEventType), required: true },
    quantity: { type: Number, required: true },
    quantityBefore: { type: Number, required: true },
    quantityAfter: { type: Number, required: true },
    unitPrice: { type: Number },
    totalPrice: { type: Number },
    currency: { type: String },
    storeId: { type: String },
    storeName: { type: String },
    sourceType: { type: String, enum: Object.values(CabinetEventSourceType), required: true },
    sourceId: { type: String },
    reason: { type: String },
    notes: { type: String },
  },
  {
    timestamps: { createdAt: true, updatedAt: false },
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

cabinetEventSchema.index({ householdId: 1, createdAt: -1 });
cabinetEventSchema.index({ householdId: 1, cabinetItemId: 1, createdAt: -1 });
cabinetEventSchema.index({ householdId: 1, medicineId: 1, createdAt: -1 });
cabinetEventSchema.index({ householdId: 1, eventType: 1, createdAt: -1 });

export const CabinetEventModel = mongoose.model('CabinetEvent', cabinetEventSchema);
export type CabinetEventDocument = mongoose.InferSchemaType<typeof cabinetEventSchema> & {
  _id: mongoose.Types.ObjectId;
};
