import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CouchService } from '../../data/services/couch.service';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { TimeGroupDeletedEvent } from 'src/modules/item-related/time-group/domain/entities/event/time-group-deleted.event';
import { TimeGroupChangeStatusEvent } from 'src/modules/item-related/time-group/domain/entities/event/time-group-change-status.event';
import { TimeGroupUpdatedEvent } from 'src/modules/item-related/time-group/domain/entities/event/time-group-updated.event';

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

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

@EventsHandler(TimeGroupChangeStatusEvent, TimeGroupUpdatedEvent)
export class TimeGroupUpdatedHandler
  implements IEventHandler<TimeGroupChangeStatusEvent>
{
  constructor(private couchService: CouchService) {}

  async handle(event: TimeGroupChangeStatusEvent) {
    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,
        },
        'time_groups',
      );
    } else if (dataOld?.status != data.status) {
      await this.couchService.deleteDoc(
        {
          _id: data.id,
          ...data,
        },
        'time_groups',
      );
    }

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