import mongoose from 'mongoose';
import {
  StorageLocation,
  ItemStatus,
  FreshnessUrgency,
  FreshnessSource,
  ServingUnit,
} from '@meshitrack/shared';

const freshnessEstimateSchema = new mongoose.Schema(
  {
    estimatedExpiryDate: { type: Date, required: true },
    daysRemaining: { type: Number, required: true },
    urgency: { type: String, enum: Object.values(FreshnessUrgency), required: true },
    source: { type: String, enum: Object.values(FreshnessSource), required: true },
  },
  { _id: false },
);

const pantryItemSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    productId: { type: String, required: true },
    productName: { type: String, required: true },
    storageLocation: { type: String, enum: Object.values(StorageLocation), required: true },
    quantity: { type: Number, required: true, min: 0 },
    unit: { type: String, enum: Object.values(ServingUnit), required: true },
    purchaseDate: { type: Date, required: true },
    expirationDate: { type: Date },
    openedDate: { type: Date },
    preparedDate: { type: Date },
    status: {
      type: String,
      enum: Object.values(ItemStatus),
      default: ItemStatus.SEALED,
      required: true,
    },
    freshnessEstimate: { type: freshnessEstimateSchema, required: true },
    notes: { type: String },
    purchasePrice: { type: Number },
    storeId: { type: String },
    createdBy: { type: String, required: true },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

pantryItemSchema.index({ householdId: 1, status: 1, 'freshnessEstimate.urgency': 1 });
pantryItemSchema.index({ householdId: 1, storageLocation: 1, status: 1 });
pantryItemSchema.index({ householdId: 1, productId: 1, status: 1 });
pantryItemSchema.index({ householdId: 1, 'freshnessEstimate.estimatedExpiryDate': 1 });

export const PantryItemModel = mongoose.model('PantryItem', pantryItemSchema);
export type PantryItemDocument = mongoose.InferSchemaType<typeof pantryItemSchema> & {
  _id: mongoose.Types.ObjectId;
};
