import mongoose from 'mongoose';

import Reserve, { IReserve, IReserveDoc, IReserveItem, IReserveSummary } from '../models/Reserve.model';
import { getBBCDatesByBorrower } from './bbcDates.db';

export const getReserveDocs = async (bbcDateIds: mongoose.Types.ObjectId[]) => {
  return Reserve.aggregate<IReserveDoc>([
    {
      $match: {
        'bbcDateId': {
          $in: bbcDateIds
        }
      }
    },
  ]);
};

export const saveReserveDoc = async (bbcDateId: mongoose.Types.ObjectId, reserveUpdate: Partial<IReserve>) => {
  return Reserve
    .findOneAndUpdate({ bbcDateId }, reserveUpdate, { upsert: true, new: true })
    .lean();
};

export const copyReserveWithoutSaving = async (bbcDateId: mongoose.Types.ObjectId, items: IReserveItem[], summary: IReserveSummary) => {
  return new Reserve({ bbcDateId, items, summary });
}

export const getLastReserveDocs = async (bbcDateId: string, borrowerId: string) => {
  const bbcDates = await getBBCDatesByBorrower(borrowerId);
  const bbcDateIds = bbcDates.map((bbc) => bbc._id);
  return Reserve.aggregate<IReserveDoc>([
    {
      $match:
        {
          $and: [
            { 'bbcDateId': { $in: bbcDateIds } },
            { 'bbcDateId': { $ne: new mongoose.Types.ObjectId(bbcDateId) } },
          ],
        },
    },
    {
      $sort: { 'updatedAt': -1 }
    },
    {
      $limit: 1
    }
  ]);
};
