import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { EMPTY_UUID } from 'src/core/strings/constants/base.constants';
import { ItemCreatedEvent } from 'src/modules/item-related/item/domain/entities/event/item-created.event';
import { SeasonPeriodDataService } from 'src/modules/season-related/season-period/data/services/season-period-data.service';
import { Not } from 'typeorm';
import { ItemRateModel } from '../../../data/models/item-rate.model';
import { ItemRateDataService } from '../../../data/services/item-rate-data.service';

@EventsHandler(ItemCreatedEvent)
export class SeasonPeriodHolidayHandler
  implements IEventHandler<ItemCreatedEvent>
{
  constructor(
    private seasonService: SeasonPeriodDataService,
    private dataService: ItemRateDataService,
  ) {}

  async handle(event: ItemCreatedEvent) {
    const rates = [];
    const seasons = await this.seasonService.getManyByOptions({
      where: {
        id: Not(EMPTY_UUID),
      },
    });

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

    if (seasons.length) {
      for (const season of seasons) {
        const rate = new ItemRateModel();
        rate.item_id = event.data.id;
        rate.season_period_id = season.id;
        rate.price =
          Number(event.data.data.total_price) != 0
            ? event.data.data.total_price
            : event.data.data.base_price;

        rates.push(rate);
      }
    }

    // create batch
    await this.dataService.createBatch(queryRunner, ItemRateModel, rates);
  }
}
