import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { ChangeDocEvent } from 'src/modules/configuration/couch/domain/events/change-doc.event';
import { VipCodeDataService } from '../../../data/services/vip-code-data.service';
import { VipCodeModel } from '../../../data/models/vip-code.model';
import { CouchService } from 'src/modules/configuration/couch/data/services/couch.service';

@EventsHandler(ChangeDocEvent)
export class CreateVipCodeHandler implements IEventHandler<ChangeDocEvent> {
  constructor(
    private dataService: VipCodeDataService,
    private couchService: CouchService,
  ) {}

  async handle(event: ChangeDocEvent) {
    const database = event.data.database;
    const data = event.data.data;

    if (database != 'vip_code') return;

    const queryRunner = this.dataService
      .getRepository()
      .manager.connection.createQueryRunner();

    // jika delete
    if (data._deleted ?? false) {
    } else {
      const dataMapped = {
        ...data,
        id: data._id ?? data.id,
        vip_category_id: data.vip_category?._id ?? data.vip_category?.id,
      };
      console.log({ dataMapped });
      try {
        await this.dataService.create(queryRunner, VipCodeModel, dataMapped);
      } catch (error) {
        await this.couchService.createDoc(data, 'error_vip_code');
      }
    }
  }
}
