import {
  HttpStatus,
  Injectable,
  UnprocessableEntityException,
} from '@nestjs/common';
import {
  EventTopics,
  columnUniques,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { RefundEntity } from '../../entities/refund.entity';
import { RefundModel } from '../../../data/models/refund.model';
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
import { RefundCreatedEvent } from '../../entities/event/refund-created.event';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { In, Not } from 'typeorm';
import { generateInvoiceCodeHelper } from 'src/modules/transaction/transaction/domain/usecases/managers/helpers/generate-invoice-code.helper';

@Injectable()
export class CreateRefundManager extends BaseCreateManager<RefundEntity> {
  async beforeProcess(): Promise<void> {
    const refund_items = this.data.refund_items?.map((item) => {
      return {
        transaction_item: item,
        qty_refund: item.qty_refund,
        refund_total: item.refund_total,
        refund_sub_total: item.refund_sub_total,
      };
    });

    const exist = await this.dataService.getOneByOptions({
      where: {
        transaction_id: this.data.transaction.id,
        status: Not(In([STATUS.CANCEL])),
      },
    });
    if (exist) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! pengembalian pemesanan dengan nomor invoice ${this.data.transaction.invoice_code} telah dibuat`,
        error: 'Unprocessable Entity',
      });
    }

    const transaction = await this.dataServiceFirstOpt.getOneByOptions({
      where: {
        id: this.data.transaction.id,
        status: STATUS.SETTLED,
      },
    });

    if (!transaction) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! hanya pemesanan dengan status ${STATUS.SETTLED} dapat dikembalikan`,
        error: 'Unprocessable Entity',
      });
    }

    Object.assign(this.data, {
      refund_items: refund_items,
      code: await generateInvoiceCodeHelper(this.dataService, 'RF'),
    });
    return;
  }

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

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

  get uniqueColumns(): columnUniques[] {
    return [];
  }

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

  get entityTarget(): any {
    return RefundModel;
  }
}
