import mongoose from 'mongoose';

const shoppingItemSchema = new mongoose.Schema(
  {
    id: { type: String, required: true }, // Client or server generated tracking UUID
    productId: { type: String },
    customName: { type: String },
    quantity: { type: Number, required: true },
    unit: { type: String, required: true },
    checked: { type: Boolean, required: true, default: false },
    checkedAt: { type: Date },
    checkedBy: { type: String },
    estimatedPrice: { type: Number },
    actualPrice: { type: Number },
    storeId: { type: String },
    notes: { type: String },
    category: { type: String },
    addedToPantry: { type: Boolean, required: true, default: false },
  },
  { _id: false },
);

const shoppingListSourceSchema = new mongoose.Schema(
  {
    type: { type: String, required: true }, // values from ShoppingListSourceType
    referenceId: { type: String },
  },
  { _id: false },
);

const shoppingListSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    name: { type: String, required: true },
    items: { type: [shoppingItemSchema], required: true, default: [] },
    status: { type: String, required: true }, // values from ShoppingListStatus
    createdFrom: {
      type: shoppingListSourceSchema,
      required: false,
    },
    mealPlanId: { type: String },
    totalEstimatedCost: { type: Number },
    preferredStoreId: { type: String },
    completedAt: { type: Date },
    createdBy: { type: String, required: true },
  },
  { timestamps: true },
);

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

export const ShoppingListModel = mongoose.model('ShoppingList', shoppingListSchema);
export type ShoppingListDocument = mongoose.InferSchemaType<typeof shoppingListSchema> & {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
};
