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 { TicketDataService } from '../../data/services/ticket.service';
import { QueueOrder } from '../../domain/entities/order.entity';
import { QueueTicket } from '../../domain/entities/ticket.entity';
import { QueueItem } from '../../domain/entities/queue-item.entity';

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

  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') return;

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

    const { id, customer_name, customer_phone, invoice_code } = transaction;
    const current_date = new Date().valueOf();
    const customerOrder = {
      code: invoice_code,
      customer: customer_name,
      phone: customer_phone,
      date: current_date,
      transaction_id: id,
    };

    const items = transaction.items.map<QueueItem>((item) => {
      return {
        item_id: item.item_id,
        qty: item.qty,
      };
    });

    const ticket: QueueTicket = { ...customerOrder, items };
    const order: QueueOrder = { ...customerOrder, tickets: [ticket] };

    this.queueService.createQueueOrder(order);
  }
}
