import mongoose from 'mongoose';
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';

const medicineSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    name: { type: String, required: true },
    form: { type: String, enum: Object.values(MedicineForm), required: true },
    strength: { type: Number, required: true },
    strengthUnit: { type: String, enum: Object.values(StrengthUnit), required: true },
    category: { type: String, enum: Object.values(MedicineCategory), required: true },
    notes: { type: String },
    tags: { type: [String], default: [] },
    createdBy: { type: String, required: true },
    isDeleted: { type: Boolean, default: false },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

medicineSchema.index(
  { householdId: 1, name: 'text', tags: 'text' },
  { name: 'medicine_text_search' },
);
medicineSchema.index({ householdId: 1, category: 1 });
medicineSchema.index(
  { householdId: 1, name: 1, strength: 1, strengthUnit: 1, form: 1 },
  { name: 'medicine_dedup' },
);

export const MedicineModel = mongoose.model('Medicine', medicineSchema);
export type MedicineDocument = mongoose.InferSchemaType<typeof medicineSchema> & {
  _id: mongoose.Types.ObjectId;
};
