import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CouchService } from '../../data/services/couch.service';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { SeasonPeriodDeletedEvent } from 'src/modules/season-related/season-period/domain/entities/event/season-period-deleted.event';
import { SeasonPeriodChangeStatusEvent } from 'src/modules/season-related/season-period/domain/entities/event/season-period-change-status.event';
import { SeasonPeriodUpdatedEvent } from 'src/modules/season-related/season-period/domain/entities/event/season-period-updated.event';

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

  async handle(event: SeasonPeriodDeletedEvent) {
    const data = await this.couchService.deleteDoc(
      {
        _id: event.data.id,
        ...event.data.data,
      },
      'season_period',
    );
  }
}

@EventsHandler(SeasonPeriodChangeStatusEvent, SeasonPeriodUpdatedEvent)
export class SeasonPeriodUpdatedHandler
  implements IEventHandler<SeasonPeriodChangeStatusEvent>
{
  constructor(private couchService: CouchService) {}

  async handle(event: SeasonPeriodChangeStatusEvent) {
    const dataOld = event.data.old;
    const data = event.data.data;

    // change status to active
    if (dataOld?.status != data.status && data.status == STATUS.ACTIVE) {
      await this.couchService.createDoc(
        {
          _id: data.id,
          ...data,
        },
        'season_period',
      );
    } else if (dataOld?.status != data.status) {
      await this.couchService.deleteDoc(
        {
          _id: data.id,
          ...data,
        },
        'season_period',
      );
    }

    // update
    else {
      await this.couchService.updateDoc(
        {
          _id: data.id,
          ...data,
        },
        'season_period',
      );
    }
  }
}
