import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { TransactionDataService } from 'src/modules/transaction/transaction/data/services/transaction-data.service';
import {
  TransactionChangeStatusEvent,
  TransactionCreateQueueEvent,
} from 'src/modules/transaction/transaction/domain/entities/event/transaction-change-status.event';
import { GenerateQueueManager } from '../../domain/usecases/generate-queue.manager';

@EventsHandler(TransactionChangeStatusEvent, TransactionCreateQueueEvent)
export class QueueTransactionHandler
  implements IEventHandler<TransactionChangeStatusEvent>
{
  constructor(
    private readonly dataService: TransactionDataService,
    private readonly queueGenerateManager: GenerateQueueManager,
  ) {}

  async handle(event: TransactionChangeStatusEvent) {
    const process_data = event.data.data;

    /**
     * If data still in process (not settled) then don't create the queue order
     */
    if (process_data?.status != 'settled' || process_data?.pos_number != null)
      return;

    const transaction = await this.dataService.getOneByOptions({
      where: {
        id: event.data.id,
      },
      relations: [
        'customer_category',
        'items',
        'items.item',
        'items.item.bundling_items',
      ],
    });

    await this.queueGenerateManager.generate(transaction);
  }
}
