import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CouchService } from '../../data/services/couch.service';
import { VipCategoryDeletedEvent } from 'src/modules/transaction/vip-category/domain/entities/event/vip-category-deleted.event';
import { VipCategoryChangeStatusEvent } from 'src/modules/transaction/vip-category/domain/entities/event/vip-category-change-status.event';
import { VipCategoryUpdatedEvent } from 'src/modules/transaction/vip-category/domain/entities/event/vip-category-updated.event';
import { STATUS } from 'src/core/strings/constants/base.constants';

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

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

@EventsHandler(VipCategoryChangeStatusEvent, VipCategoryUpdatedEvent)
export class VipCategoryUpdatedHandler
  implements IEventHandler<VipCategoryChangeStatusEvent>
{
  constructor(private couchService: CouchService) {}

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

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