import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { ChangeDocEvent } from 'src/modules/configuration/couch/domain/events/change-doc.event';
import { PosLogService } from '../../data/services/pos-log.service';
import { PosLogModel } from '../../data/models/pos-log.model';
import { PosLogType } from '../entities/pos-log.entity';

@EventsHandler(ChangeDocEvent)
export class RecordPosLogHandler implements IEventHandler<ChangeDocEvent> {
  constructor(private dataService: PosLogService) {}

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

      if (!['pos_cash_activity', 'pos_activity'].includes(database)) return;

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

      const activity = new PosLogModel();

      Object.assign(activity, {
        id: data._id,
        type: PosLogType[data.type],
        total_balance: data.withdrawal_cash ?? data.opening_cash_balance,
        pos_number: data.pos_number,
        pos_name: data.pos_name,
        creator_id: data.pos_admin?.id,
        creator_name: data.pos_admin?.name ?? data.pos_admin?.username,
        drawn_by_id: data.withdraw_user?.id,
        drawn_by_name: data.withdraw_user?.name ?? data.withdraw_user?.username,
        created_at: data.created_at,
      });

      await this.dataService.create(queryRunner, PosLogModel, activity);
    } catch (error) {
      console.log('error handling pos activity couch');
    }
  }
}
