import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CouchService } from '../../data/services/couch.service';
import { SeasonTypeDeletedEvent } from 'src/modules/season-related/season-type/domain/entities/event/season-type-deleted.event';
import { SeasonTypeChangeStatusEvent } from 'src/modules/season-related/season-type/domain/entities/event/season-type-change-status.event';
import { SeasonTypeUpdatedEvent } from 'src/modules/season-related/season-type/domain/entities/event/season-type-updated.event';
import { SeasonPeriodDataService } from 'src/modules/season-related/season-period/data/services/season-period-data.service';

@EventsHandler(SeasonTypeDeletedEvent)
export class SeasonTypeDeletedHandler
  implements IEventHandler<SeasonTypeDeletedEvent>
{
  constructor(private couchService: CouchService) {}

  async handle(event: SeasonTypeDeletedEvent) {
    console.log('deleted session type');
  }
}

@EventsHandler(SeasonTypeChangeStatusEvent, SeasonTypeUpdatedEvent)
export class SeasonTypeUpdatedHandler
  implements IEventHandler<SeasonTypeChangeStatusEvent>
{
  constructor(
    private couchService: CouchService,
    private seasonPeriodService: SeasonPeriodDataService,
  ) {}

  async handle(event: SeasonTypeChangeStatusEvent) {
    const data = event.data.data;
    const typeID = data.id;
    const periods = await this.seasonPeriodService.getManyByOptions({
      where: {
        season_type_id: typeID,
      },
      relations: ['season_type'],
    });

    for (const period of periods) {
      const dataID = period.id;
      const couchData = await this.couchService.getDoc(dataID, 'season_period');
      if (couchData) {
        await this.couchService.updateDoc(
          {
            _id: dataID,
            ...period,
          },
          'season_period',
        );
      }
    }
  }
}
