import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { SeasonPeriodPriceUpdatedEvent } from '../../entities/event/season-period-price-updated.event';
import { SeasonPeriodReadService } from '../../../data/services/season-period-read.service';
import { SeasonPeriodDataService } from '../../../data/services/season-period-data.service';
import { SeasonPeriodModel } from '../../../data/models/season-period.model';
import { ItemRateDataService } from 'src/modules/item-related/item-rate/data/services/item-rate-data.service';
import { ItemRateModel } from 'src/modules/item-related/item-rate/data/models/item-rate.model';
import { IsNull } from 'typeorm';

@EventsHandler(SeasonPeriodPriceUpdatedEvent)
export class SeasonPeriodPriceUpdatedHandler
  implements IEventHandler<SeasonPeriodPriceUpdatedEvent>
{
  constructor(
    private readService: SeasonPeriodReadService,
    private dataService: SeasonPeriodDataService,
    private rateDataService: ItemRateDataService,
  ) {}

  async handle(event: SeasonPeriodPriceUpdatedEvent) {
    const datas = await this.readService
      .getManyByOptions({
        where: {
          season_type_id: event.data.data.season_period?.id,
        },
      })
      .then((data) => {
        return data.map((item) => {
          return {
            ...item,
            item_rates: event.data.data.item_rates,
          };
        });
      });

    const queryRunner = this.dataService
      .getRepository()
      .manager.connection.createQueryRunner();

    await this.dataService.createBatch(queryRunner, SeasonPeriodModel, datas);

    await this.deleteUnusedItem();
  }

  async deleteUnusedItem() {
    const queryRunnerItem = this.rateDataService
      .getRepository()
      .manager.connection.createQueryRunner();

    await this.rateDataService.deleteByOptions(queryRunnerItem, ItemRateModel, {
      where: {
        season_period_id: IsNull(),
      },
    });
  }
}
