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 { TransactionPaymentType } from '../../../constants';

@Injectable()
export class ConfirmDataTransactionManager extends BaseUpdateStatusManager<TransactionEntity> {
  protected relations = ['items', 'items.bundling_items'];
  getResult(): string {
    return `Success active data ${this.result.invoice_code}`;
  }

  async validateProcess(): Promise<void> {
    if (
      [
        TransactionPaymentType.BANK_TRANSFER,
        TransactionPaymentType.QRIS,
      ].includes(this.data.payment_type) &&
      (!this.data.payment_date ||
        !this.data.payment_total ||
        !this.data.payment_type_method_number ||
        !this.data.payment_type_method_name)
    ) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! tolong lengkapi data terlebih dahulu`,
        error: 'Unprocessable Entity',
      });
    }

    return;
  }

  async beforeProcess(): Promise<void> {
    const old_status = this.oldData.status;

    if (
      ![STATUS.PENDING, STATUS.REJECTED, STATUS.EXPIRED].includes(old_status)
    ) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! hanya pemesanan dengan status ${STATUS.PENDING}, ${STATUS.REJECTED}, ${STATUS.EXPIRED} dapat dikonfirmasi`,
        error: 'Unprocessable Entity',
      });
    }

    Object.assign(this.data, {
      status: STATUS.WAITING,
      reconciliation_status: [
        TransactionPaymentType.COUNTER,
        TransactionPaymentType.MIDTRANS,
      ].includes(this.oldData.payment_type)
        ? null
        : STATUS.PENDING,
    });
    return;
  }

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

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

  get entityTarget(): any {
    return TransactionModel;
  }

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