import mongoose from 'mongoose';

import {
  IInventorySeasonalRatesDoc,
  IInventorySeasonalRatesItemDoc,
  InventorySeasonalEntryModel,
} from '../models/InventorySeasonalRates.model';

export const getNewSeasonalRates = async (borrowerId: string) => {
  return <IInventorySeasonalRatesDoc>{
    borrowerId: new mongoose.Types.ObjectId(borrowerId),
    items: [],
  };
}

export const getSeasonalRates = async (borrowerId: string) => {
  const foundRates = await InventorySeasonalEntryModel.findOne({ borrowerId });
  if (foundRates) {
    return foundRates;
  }
  return await getNewSeasonalRates(borrowerId);
}

export const saveSeasonalRates = async (borrowerId: string, rates: IInventorySeasonalRatesItemDoc[]) => {
  const foundRates = await InventorySeasonalEntryModel.findOne({ borrowerId });
  if (foundRates) {
    const mappedRates = rates.map((rate) => {
      const { _id, ...restRate } = rate;
      return restRate;
    });
    await InventorySeasonalEntryModel.findByIdAndUpdate(foundRates._id, { items: mappedRates });
  } else {
    const mappedRates = rates.map((rate) => {
      const { _id, ...restRate } = rate;
      return restRate;
    });
    const newRates = await InventorySeasonalEntryModel.create({ borrowerId, items: mappedRates });
    await newRates.save();
  }
}
