import { HttpStatus } from '@nestjs/common';
import { UnprocessableEntityException } from '@nestjs/common';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { TransactionType } from 'src/modules/transaction/transaction/constants';
import { CreateTransactionManager } from 'src/modules/transaction/transaction/domain/usecases/managers/create-transaction.manager';
import { generateInvoiceCodeHelper } from 'src/modules/transaction/transaction/domain/usecases/managers/helpers/generate-invoice-code.helper';
import { mappingRevertTransaction } from 'src/modules/transaction/transaction/domain/usecases/managers/helpers/mapping-transaction.helper';
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
import { v4 as uuidv4 } from 'uuid';

export class CreateBookingManager extends CreateTransactionManager {
  async beforeProcess(): Promise<void> {
    mappingRevertTransaction(this.data, TransactionType.ONLINE);

    const id = uuidv4();
    const invoiceCode = await generateInvoiceCodeHelper(
      this.dataService,
      'BOOK',
    );

    try {
      const { token, redirect_url } = await this.dataServiceFirstOpt.create({
        ...this.data,
        id,
      });
      Object.assign(this.data, {
        payment_midtrans_token: token,
        payment_midtrans_url: redirect_url,
      });
    } catch (error) {
      console.log({ error });
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! transaksi telah terbuat, silahkan periksa email untuk melanjutkan pembayaran`,
        error: 'Unprocessable Entity',
      });
    }

    Object.assign(this.data, {
      id,
      invoice_code: invoiceCode,
      status: STATUS.PENDING,
      invoice_date: new Date(),
    });
    return;
  }

  async afterProcess(): Promise<void> {
    const whatsapp = new WhatsappService();
    console.log(`/snap/v4/redirection/${this.data.payment_midtrans_token}`);
    console.log(this.data.payment_midtrans_url);
    await whatsapp.bookingRegister(
      {
        phone: this.data.customer_phone,
        code: this.data.invoice_code,
        name: this.data.customer_name,
        time: this.data.booking_date,
        id: this.data.id,
      },
      this.data.payment_total,
      `snap/v4/redirection/${this.data.payment_midtrans_token}`,
    );
  }
}
