import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CouchService } from '../../data/services/couch.service';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { PaymentMethodDeletedEvent } from 'src/modules/transaction/payment-method/domain/entities/event/payment-method-deleted.event';
import { PaymentMethodUpdatedEvent } from 'src/modules/transaction/payment-method/domain/entities/event/payment-method-updated.event';
import { PaymentMethodChangeStatusEvent } from 'src/modules/transaction/payment-method/domain/entities/event/payment-method-change-status.event';

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

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

@EventsHandler(PaymentMethodChangeStatusEvent, PaymentMethodUpdatedEvent)
export class PaymentMethodUpdatedHandler
  implements IEventHandler<PaymentMethodChangeStatusEvent>
{
  constructor(private couchService: CouchService) {}

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

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