import { OrganizerFillModel } from '../../schemas/organizer-fill.schema.js';
import type { OrganizerFillStatus } from '@meshitrack/shared';

interface OrganizerFillItemData {
  medicineId: string;
  medicineName: string;
  quantityNeeded: number;
  quantityTaken: number;
  wasShort: boolean;
  shortage: number;
  deductions: { cabinetItemId: string; quantityTaken: number }[];
}

interface CreateOrganizerFillData {
  householdId: string;
  userId: string;
  regimenId: string;
  regimenName: string;
  numberOfDays: number;
  fillDate: Date;
  items: OrganizerFillItemData[];
  status: OrganizerFillStatus;
  notes?: string;
}

interface FindByHouseholdQuery {
  regimenId?: string;
  status?: OrganizerFillStatus;
  cursor?: string;
  limit: number;
}

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

    if (query.regimenId) filter['regimenId'] = query.regimenId;
    if (query.status) filter['status'] = query.status;

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

    const limit = query.limit;
    const items = await OrganizerFillModel.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 OrganizerFillModel.findOne({ _id: id, householdId }).lean().exec();
  }

  public async create(data: CreateOrganizerFillData) {
    const fill = new OrganizerFillModel(data);
    const saved = await fill.save();
    return saved.toObject();
  }

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