import mongoose from 'mongoose';

import { getBBCDatesByBorrower } from './bbcDates.db';
import {
  CollateralAdjustment,
  ICollateralAdjustment,
  ICollateralAdjustmentDoc,
  ICollateralAdjustmentItem,
  ICollateralAdjustmentSummary,
} from '../models/CollateralAdjustment.model';

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

export const saveCollateralAdjustmentDoc = async (bbcDateId: mongoose.Types.ObjectId, collateralAdjustmentUpdate: Partial<ICollateralAdjustment>) => {
  return CollateralAdjustment
    .findOneAndUpdate({ bbcDateId }, collateralAdjustmentUpdate, { upsert: true, new: true })
    .lean();
};

export const copyCollateralAdjustmentWithoutSaving = async (bbcDateId: mongoose.Types.ObjectId, items: ICollateralAdjustmentItem[], summary: ICollateralAdjustmentSummary) => {
  return new CollateralAdjustment({ bbcDateId, items, summary });
};

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