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

import { getLoanProductBalance as getLoanProductBalanceDB } from '../db/loan-products.db';

import { LoanStatementBalanceService } from './loan-statement-balance.service';
import { EMonthEndDataType } from '../models/MonthEndData.Model';
import { MonthEndDataService } from './month-end-data.service';

export class LoanStatementEffectsService {
  constructor(
    private readonly loanStatementBalanceService: LoanStatementBalanceService,
    private readonly monthEndDataService: MonthEndDataService,
  ) {
  }

  async saveMonthData(productId: string, statementDate: Date) {
    if (dayjs(statementDate).date() !== 1) {
      return;
    }
    const balance = await getLoanProductBalanceDB(productId, statementDate);
    const lastTransaction = await this.loanStatementBalanceService.getLastStatementTransactionForDate(productId, statementDate);
    const month = dayjs(statementDate).subtract(1, 'd').month() + 1;
    const year = dayjs(statementDate).subtract(1, 'd').year();

    const keptData = {
      [EMonthEndDataType.BALANCE]: balance?.balance ?? 0,
      [EMonthEndDataType.FLOATED_BALANCE]: balance?.floatedBalance ?? 0,
      [EMonthEndDataType.STATEMENT_BALANCE]: lastTransaction?.balance ?? 0,
    };
    await Promise.all(Object.entries(keptData).map(async ([dataType, dataValue]) => {
      await this.monthEndDataService.upsertMonthEndData({
        productId: new mongoose.Types.ObjectId(productId),
        year,
        month,
        dataType: dataType as EMonthEndDataType,
        dataValue,
      });
    }));
  }
}
