import {
  HttpStatus,
  Injectable,
  UnprocessableEntityException,
} from '@nestjs/common';
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
import { TransactionEntity } from '../../entities/transaction.entity';
import {
  EventTopics,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TransactionModel } from '../../../data/models/transaction.model';
import { TransactionChangeStatusEvent } from '../../entities/event/transaction-change-status.event';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { generateInvoiceCodeHelper } from './helpers/generate-invoice-code.helper';
import { TransactionPaymentType } from '../../../constants';
import { apm } from 'src/core/apm';

@Injectable()
export class ConfirmTransactionManager extends BaseUpdateStatusManager<TransactionEntity> {
  protected relations = ['items'];

  getResult(): string {
    return `Success active data ${this.result.invoice_code}`;
  }

  async validateProcess(): Promise<void> {
    if (this.oldData.status != STATUS.DRAFT) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! hanya data booking dengan status ${STATUS.DRAFT} yang dapat di${this.dataStatus}`,
        error: 'Unprocessable Entity',
      });
    }
    return;
  }

  async beforeProcess(): Promise<void> {
    const freeTransaction = this.data.payment_total < 1;

    if (this.data.payment_type == TransactionPaymentType.MIDTRANS) {
      try {
        const { token, redirect_url } = await this.dataServiceFirstOpt.create(
          this.oldData,
        );
        Object.assign(this.data, {
          payment_midtrans_token: token,
          payment_midtrans_url: redirect_url,
        });
      } catch (error) {
        apm.captureError(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, {
      invoice_code: await generateInvoiceCodeHelper(this.dataService, 'INV'),
      status: freeTransaction ? STATUS.ACTIVE : STATUS.PENDING,
      invoice_date: new Date(),
    });
    return;
  }

  async afterProcess(): Promise<void> {
    return;
  }

  get validateRelations(): validateRelations[] {
    return [];
  }

  get entityTarget(): any {
    return TransactionModel;
  }

  get eventTopics(): EventTopics[] {
    return [
      {
        topic: TransactionChangeStatusEvent,
        data: this.data,
      },
    ];
  }
}
