import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { SeasonPeriodCreatedEvent } from '../../entities/event/season-period-created.event';
import { SeasonPeriodDataService } from '../../../data/services/season-period-data.service';
import { SeasonPeriodModel } from '../../../data/models/season-period.model';

@EventsHandler(SeasonPeriodCreatedEvent)
export class SeasonPeriodHolidayHandler
  implements IEventHandler<SeasonPeriodCreatedEvent>
{
  constructor(private dataService: SeasonPeriodDataService) {}

  async handle(event: SeasonPeriodCreatedEvent) {
    const queryRunner = this.dataService
      .getRepository()
      .manager.connection.createQueryRunner();

    if (event.data.data.holidays?.length) {
      // foreach holiday
      for (const holiday of event.data.data.holidays) {
        const holidayDate = new SeasonPeriodModel();

        holidayDate.holiday_name = holiday.holiday_name;
        holidayDate.start_date = holiday.start_date;
        holidayDate.end_date = holiday.end_date;
        holidayDate.created_at = event.data.data.created_at;
        holidayDate.creator_id = event.data.data.creator_id;
        holidayDate.creator_name = event.data.data.creator_name;
        holidayDate.updated_at = event.data.data.updated_at;
        holidayDate.season_type = event.data.data.season_type;
        holidayDate.item_rates = event.data.data.item_rates.map((item) => {
          delete item['id'];

          return item;
        });
        holidayDate.priority = 1;

        await this.dataService.create(
          queryRunner,
          SeasonPeriodModel,
          holidayDate,
        );
      }

      // delete data
      await this.dataService.deleteById(
        queryRunner,
        SeasonPeriodModel,
        event.data.id,
      );
    }
  }
}
