import mongoose, { type Document } from 'mongoose';

const { Schema, model } = mongoose;

const purchaseItemSchema = new Schema(
  {
    medicineProductId: { type: String },
    medicineId: { type: String },
    foodProductId: { type: String },
    name: { type: String, required: true },
    quantity: { type: Number, required: true },
    unit: { type: String, required: true },
    actualPrice: { type: Number },
    currency: { type: String },
    priceRecordId: { type: String },
    addedToCabinet: { type: Boolean, default: false },
  },
  { _id: false },
);

const purchaseSchema = new Schema(
  {
    householdId: { type: String, required: true },
    storeId: { type: String, required: true },
    storeName: { type: String, required: true },
    status: { type: String, enum: ['ordered', 'in_cabinet'], required: true },
    items: { type: [purchaseItemSchema], required: true },
    notes: { type: String },
    purchasedAt: { type: Date, required: true },
    receivedAt: { type: Date },
    createdBy: { type: String, required: true },
    isDeleted: { type: Boolean, default: false },
  },
  { timestamps: true },
);

purchaseSchema.index({ householdId: 1, status: 1, purchasedAt: -1 });
purchaseSchema.index({ householdId: 1, storeId: 1 });
purchaseSchema.index({ householdId: 1, 'items.medicineProductId': 1 });

export type PurchaseDocument = Document & {
  householdId: string;
  storeId: string;
  storeName: string;
  status: string;
  items: Array<{
    medicineProductId?: string;
    medicineId?: string;
    foodProductId?: string;
    name: string;
    quantity: number;
    unit: string;
    actualPrice?: number;
    currency?: string;
    priceRecordId?: string;
    addedToCabinet: boolean;
  }>;
  notes?: string;
  purchasedAt: Date;
  receivedAt?: Date;
  createdBy: string;
  isDeleted: boolean;
  createdAt: Date;
  updatedAt: Date;
};

export const PurchaseModel = model<PurchaseDocument>('Purchase', purchaseSchema);
