import mongoose from 'mongoose';
import { MealType, MealPlanStatus } from '@meshitrack/shared';

const nutritionInfoSchema = new mongoose.Schema(
  {
    calories: { type: Number, required: true, min: 0 },
    protein: { type: Number, required: true, min: 0 },
    carbs: { type: Number, required: true, min: 0 },
    fat: { type: Number, required: true, min: 0 },
    fiber: { type: Number, min: 0 },
    sugar: { type: Number, min: 0 },
    sodium: { type: Number, min: 0 },
    saturatedFat: { type: Number, min: 0 },
    cholesterol: { type: Number, min: 0 },
  },
  { _id: false },
);

const plannedMealSchema = new mongoose.Schema(
  {
    id: { type: String, required: true }, // UUID for drag-and-drop reference
    type: { type: String, enum: Object.values(MealType), required: true },
    recipeId: { type: String },
    recipeName: { type: String, required: true },
    servings: { type: Number, required: true, min: 0.1 },
    customName: { type: String },
    customNutrition: { type: nutritionInfoSchema },
    perServingNutrition: { type: nutritionInfoSchema, required: true },
    notes: { type: String },
  },
  { _id: false },
);

const mealPlanDaySchema = new mongoose.Schema(
  {
    date: { type: String, required: true }, // YYYY-MM-DD
    meals: { type: [plannedMealSchema], default: [] },
    dailyNutritionTotal: { type: nutritionInfoSchema, required: true },
  },
  { _id: false },
);

const mealPlanSchema = new mongoose.Schema(
  {
    householdId: { type: String, required: true },
    weekStartDate: { type: String, required: true }, // Monday of the week YYYY-MM-DD
    days: { type: [mealPlanDaySchema], required: true },
    status: {
      type: String,
      enum: Object.values(MealPlanStatus),
      required: true,
      default: MealPlanStatus.DRAFT,
    },
    shoppingListId: { type: String },
    createdBy: { type: String, required: true },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

// Unique week per household
mealPlanSchema.index({ householdId: 1, weekStartDate: 1 }, { unique: true });
mealPlanSchema.index({ householdId: 1, status: 1 });
mealPlanSchema.index({ householdId: 1, 'days.meals.recipeId': 1 });

export const MealPlanModel = mongoose.model('MealPlan', mealPlanSchema);
export type MealPlanDocument = mongoose.InferSchemaType<typeof mealPlanSchema> & {
  _id: mongoose.Types.ObjectId;
};
