import { MedicineProductModel } from '../../schemas/medicine-product.schema.js';
import type { CreateMedicineProductInput, UpdateMedicineProductInput } from '@meshitrack/shared';

interface FindByMedicineQuery {
  cursor?: string;
  limit: number;
}

export class MedicineProductsRepository {
  public async findByMedicine(householdId: string, medicineId: string, query: FindByMedicineQuery) {
    const filter: Record<string, unknown> = { householdId, medicineId, isDeleted: false };

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

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

  public async create(
    data: CreateMedicineProductInput,
    householdId: string,
    medicineId: string,
    medicineName: string,
    createdBy: string,
  ) {
    const product = new MedicineProductModel({
      ...data,
      householdId,
      medicineId,
      medicineName,
      createdBy,
    });
    const saved = await product.save();
    return saved.toObject();
  }

  public async update(id: string, householdId: string, data: UpdateMedicineProductInput) {
    return MedicineProductModel.findOneAndUpdate(
      { _id: id, householdId, isDeleted: false },
      { $set: data },
      { new: true, lean: true },
    ).exec();
  }

  public async countByMedicineId(medicineId: string): Promise<number> {
    return MedicineProductModel.countDocuments({ medicineId, isDeleted: false }).exec();
  }

  public async softDelete(id: string, householdId: string) {
    return MedicineProductModel.findOneAndUpdate(
      { _id: id, householdId, isDeleted: false },
      { $set: { isDeleted: true } },
      { new: true, lean: true },
    ).exec();
  }
}
