import mongoose from 'mongoose';
import dayjs from 'dayjs';

import { IPostponedTransaction } from '../models/PostponedTransactions.model';
import { ILoanTransactionDoc } from '../models/LoanTransaction.model';
import { CalendarService } from './calendar.service';
import { PostponedTransactionsRepository } from '../repositories/postponed-transactions.repository';

export class PostponedTransactionsService {
  constructor(
    private readonly calendarService: CalendarService,
    private readonly postponedTransactionsRepository: PostponedTransactionsRepository
  ) {
  }

  async cleanRecalculated(transactionId: string) {
    await this.postponedTransactionsRepository.cleanRecalculated(transactionId);
  }

  async createPostponedTransaction(transaction: ILoanTransactionDoc) {
    const currentDay = dayjs(new Date(transaction.date)).format('YYYY-MM-DD');
    const workingDate = await this.calendarService.getNextWorkingDay(currentDay);
    const postponedTransaction: IPostponedTransaction = {
      postponedToDate: workingDate,
      transactionId: new mongoose.Types.ObjectId(String(transaction._id)),
      productId: new mongoose.Types.ObjectId(String(transaction.productId)),
    };
    await this.postponedTransactionsRepository.createPostponedTransaction(postponedTransaction);
  }
}
