import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { TransactionChangeStatusEvent } from '../../entities/event/transaction-change-status.event';
import { SalesPriceFormulaDataService } from 'src/modules/transaction/sales-price-formula/data/services/sales-price-formula-data.service';
import { TaxDataService } from 'src/modules/transaction/tax/data/services/tax-data.service';
import { FormulaType } from 'src/modules/transaction/sales-price-formula/constants';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { TransactionDataService } from '../../../data/services/transaction-data.service';
import { TransactionModel } from '../../../data/models/transaction.model';
import { calculateSalesFormula } from 'src/modules/transaction/sales-price-formula/domain/usecases/managers/helpers/calculation-formula.helper';
import { CreateEventCalendarHelper } from 'src/modules/configuration/google-calendar/domain/usecases/managers/helpers/create-event-calanedar.helper';
import { TransactionUpdatedEvent } from '../../entities/event/transaction-updated.event';
import { PriceCalculator } from '../calculator/price.calculator';

@EventsHandler(TransactionChangeStatusEvent, TransactionUpdatedEvent)
export class SettledTransactionHandler
  implements IEventHandler<TransactionChangeStatusEvent>
{
  constructor(
    private formulaService: SalesPriceFormulaDataService,
    private taxService: TaxDataService,
    private dataService: TransactionDataService,
    private calculator: PriceCalculator,
  ) {}

  async handle(event: TransactionChangeStatusEvent) {
    const old_data = event.data.old;
    const current_data = event.data.data;
    const settled = [STATUS.ACTIVE, STATUS.SETTLED].includes(
      current_data.status,
    );
    const oldSettled = [STATUS.ACTIVE, STATUS.SETTLED].includes(
      old_data.status,
    );

    const data = await this.dataService.getOneByOptions({
      where: {
        id: event.data.id,
      },
      relations: ['items'],
    });

    if (settled || oldSettled) {
      const queryRunner = this.dataService
        .getRepository()
        .manager.connection.createQueryRunner();

      if (settled) {
        const profit_formula = await this.formulaService.getOneByOptions({
          where: {
            type: FormulaType.PROFIT_SHARE,
          },
        });

        const sales_price = await this.formulaService.getOneByOptions({
          where: {
            type: FormulaType.SALES_PRICE,
          },
        });

        const taxes = await this.taxService.getManyByOptions({
          where: {
            status: STATUS.ACTIVE,
          },
        });

        // const profit_share_value = this.calculateFormula(profit_formula.formula_string, taxes, data.payment_total_net_profit ?? 0);
        const { dpp_value, tax_datas, other } = await this.calculator.calculate(
          data,
        );

        // calculateSalesFormula(
        //   sales_price.formula_string,
        //   taxes,
        //   data.payment_total_net_profit ?? 0,
        // );

        // console.log(data, 'dsa');
        const google_calendar = await CreateEventCalendarHelper(data);

        Object.assign(data, {
          payment_total_dpp: dpp_value,
          profit_share_formula: profit_formula.formula_string,
          sales_price_formula: sales_price.formula_string,
          taxes: tax_datas,
          calendar_id: google_calendar?.id,
          calendar_link: google_calendar?.htmlLink,
          payment_total_share: other.total_profit_share,
          payment_total_tax: other.payment_total_tax,
        });
      } else if (oldSettled) {
        // console.log(data, 'data oldSettled');
        const google_calendar = await CreateEventCalendarHelper(data);

        Object.assign(data, {
          calendar_id: null,
          calendar_link: null,
        });
      }

      await this.dataService.create(queryRunner, TransactionModel, data);
    }
  }
}
