import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-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 { BatchResult } from 'src/core/response/domain/ok-response.interface';
import {
  HttpStatus,
  Injectable,
  UnprocessableEntityException,
} from '@nestjs/common';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { generateInvoiceCodeHelper } from './helpers/generate-invoice-code.helper';
import { TransactionPaymentType } from '../../../constants';

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

  async validateData(data: TransactionEntity): Promise<void> {
    if (data.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',
      });
    }

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

    Object.assign(data, {
      invoice_code: await generateInvoiceCodeHelper(this.dataService, 'INV'),
      status: freeTransaction ? STATUS.ACTIVE : STATUS.PENDING,
      invoice_date: new Date(),
    });
    return;
  }

  beforeProcess(): Promise<void> {
    return;
  }

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

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

  get entityTarget(): any {
    return TransactionModel;
  }

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

  getResult(): BatchResult {
    return this.result;
  }
}
