import { Injectable } from '@nestjs/common';
import { BaseUpdateManager } from 'src/core/modules/domain/usecase/managers/base-update.manager';
import { ItemRateEntity } from '../../entities/item-rate.entity';
import { ItemRateModel } from '../../../data/models/item-rate.model';
import { ItemRateUpdatedEvent } from '../../entities/event/item-rate-updated.event';
import {
  EventTopics,
  columnUniques,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';

@Injectable()
export class UpdateItemRateManager extends BaseUpdateManager<ItemRateEntity> {
  async validateProcess(): Promise<void> {
    return;
  }

  async beforeProcess(): Promise<void> {
    return;
  }

  async afterProcess(): Promise<void> {
    this.updateBundlingBreakdown(this.dataId);
    return;
  }

  get validateRelations(): validateRelations[] {
    return [];
  }

  get uniqueColumns(): columnUniques[] {
    return [];
  }

  get entityTarget(): any {
    return ItemRateModel;
  }

  get eventTopics(): EventTopics[] {
    return [
      {
        topic: ItemRateUpdatedEvent,
      },
    ];
  }

  async updateBundlingBreakdown(id: string) {
    const { item_id, season_period_id } =
      await this.dataService.getOneByOptions({
        where: { id },
      });
    const bundlings = await this.dataService.findBundlingByItem(item_id);

    for (const bundling of bundlings) {
      const ids = bundling.bundling_items.map((item) => item.id);
      const totalRates = await this.dataService.itemsRateTotal(
        season_period_id,
        ids,
      );
      this.dataService.updateRatesBySeasonItem(
        season_period_id,
        bundling.id,
        totalRates,
      );
    }
  }
}
