import mongoose from 'mongoose';

import Equipment, { IEquipmentDoc, IEquipmentItem, IEquipmentSummary } from '../models/Equipment.model';

export const getEquipmentDates = async (borrowerId: string) => {
  return Equipment.aggregate<IEquipmentDoc>([
    {
      $match: {
        'borrowerId': new mongoose.Types.ObjectId(borrowerId),
      },
    }, {
      $sort:
        { 'date': -1 },
    },
  ]);
};

export const getEquipment = async (borrowerId: string, date: Date) => {
  return Equipment.findOne({ 'borrowerId': new mongoose.Types.ObjectId(borrowerId), 'date': { $lte: date } }).lean();
};

export const deleteEquipment = async (borrowerId: string, date: Date) => {
  return Equipment.findOneAndDelete({ 'borrowerId': new mongoose.Types.ObjectId(borrowerId), 'date': date });
};

export const getLatestEquipments = async (borrowerId: string, date: Date) => {
  return Equipment.aggregate<IEquipmentDoc>([
    {
      $match: {
        'borrowerId': new mongoose.Types.ObjectId(borrowerId),
        'date': { $lte: date },
      },
    }, {
      $sort:
        { 'date': -1 },
    }, {
      $limit: 1,
    },
  ]);
};

export const saveEquipmentDoc = async (borrowerId: string, date: Date, items: IEquipmentItem[], summary: IEquipmentSummary) => {
  return Equipment
    .findOneAndUpdate(
      { borrowerId: new mongoose.Types.ObjectId(borrowerId), date },
      { items, summary },
      { upsert: true, new: true },
    )
    .lean();
};

export const copyEquipmentWithoutSaving = async (borrower: string, date: Date, items: IEquipmentItem[], summary: IEquipmentSummary) => {
  const notSavedEquipment = new Equipment({ borrower, date, items, summary });
  notSavedEquipment._id = null;
  return notSavedEquipment;
};
