import mongoose from 'mongoose';
import {
  DosageFrequency,
  DosageUnit,
  MedicineForm,
  StrengthUnit,
  TimeOfDay,
} from '@meshitrack/shared';

const regimenMedicationSchema = new mongoose.Schema(
  {
    medicineId: { type: String, required: true },
    medicineName: { type: String, required: true },
    medicineStrength: { type: Number, required: true },
    medicineStrengthUnit: { type: String, enum: Object.values(StrengthUnit), required: true },
    medicineForm: { type: String, enum: Object.values(MedicineForm), required: true },
    dosage: { type: Number, required: true },
    dosageUnit: { type: String, enum: Object.values(DosageUnit), required: true },
    frequency: { type: String, enum: Object.values(DosageFrequency), required: true },
    customFrequencyPerDay: { type: Number },
    timeOfDay: { type: String, enum: Object.values(TimeOfDay) },
    instructions: { type: String },
  },
  { _id: false },
);

const regimenSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    userId: { type: String, required: true },
    name: { type: String, required: true },
    isActive: { type: Boolean, default: true },
    medications: { type: [regimenMedicationSchema], required: true },
    createdBy: { type: String, required: true },
    isDeleted: { type: Boolean, default: false },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

regimenSchema.index({ householdId: 1, userId: 1, isActive: 1 });
regimenSchema.index({ householdId: 1, 'medications.medicineId': 1 });

export const RegimenModel = mongoose.model('Regimen', regimenSchema);
export type RegimenDocument = mongoose.InferSchemaType<typeof regimenSchema> & {
  _id: mongoose.Types.ObjectId;
};
