import { MealPlanModel } from '../../schemas/meal-plan.schema.js';
import type { MealPlanQueryInput, MealPlanStatus } from '@meshitrack/shared';

export class MealPlanRepository {
  public async findByHousehold(householdId: string, query: MealPlanQueryInput) {
    const filter: Record<string, unknown> = { householdId };

    if (query.cursor) {
      const id = Buffer.from(query.cursor, 'base64').toString();
      filter['_id'] = { $gt: id };
    }

    const limit = query.limit;
    const items = await MealPlanModel.find(filter)
      .sort({ _id: 1 })
      .limit(limit + 1)
      .lean()
      .exec();

    const hasMore = items.length > limit;
    const data = hasMore ? items.slice(0, limit) : items;
    const cursor =
      data.length > 0
        ? Buffer.from(data[data.length - 1]!._id.toString()).toString('base64')
        : null;

    return { data, pagination: { cursor: hasMore ? cursor : null, hasMore } };
  }

  public async findById(id: string, householdId: string) {
    return MealPlanModel.findOne({ _id: id, householdId }).lean().exec();
  }

  public async findByWeek(householdId: string, weekStartDate: string) {
    return MealPlanModel.findOne({ householdId, weekStartDate }).lean().exec();
  }

  public async create(data: Record<string, unknown>) {
    const doc = new MealPlanModel(data);
    const saved = await doc.save();
    return saved.toObject();
  }

  public async update(id: string, householdId: string, data: Record<string, unknown>) {
    return MealPlanModel.findOneAndUpdate(
      { _id: id, householdId },
      { $set: data },
      { new: true, lean: true },
    ).exec();
  }

  public async updateStatus(id: string, householdId: string, status: MealPlanStatus) {
    return MealPlanModel.findOneAndUpdate(
      { _id: id, householdId },
      { $set: { status } },
      { new: true, lean: true },
    ).exec();
  }

  public async delete(id: string, householdId: string) {
    return MealPlanModel.findOneAndDelete({ _id: id, householdId }).lean().exec();
  }
}
