import {
  HttpStatus,
  Injectable,
  UnprocessableEntityException,
} from '@nestjs/common';
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
import { RefundEntity } from '../../entities/refund.entity';
import {
  EventTopics,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { RefundModel } from '../../../data/models/refund.model';
import { RefundChangeStatusEvent } from '../../entities/event/refund-change-status.event';
import { STATUS } from 'src/core/strings/constants/base.constants';

@Injectable()
export class ConfirmRefundManager extends BaseUpdateStatusManager<RefundEntity> {
  getResult(): string {
    return `Success active data ${this.result.code}`;
  }

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

  async beforeProcess(): Promise<void> {
    const data = await this.dataService.getOneByOptions({
      where: {
        id: this.data.id,
      },
      relations: ['transaction'],
    });

    if (
      data.status == STATUS.DRAFT &&
      data.transaction.status != STATUS.SETTLED &&
      data.status == STATUS.PENDING &&
      data.transaction.status != STATUS.PROCESS_REFUND
    ) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! hanya pemesanan dengan status ${STATUS.SETTLED} dapat di${this.dataStatus}`,
        error: 'Unprocessable Entity',
      });
    }

    if (data.status == STATUS.DRAFT) {
      Object.assign(this.data, {
        request_date: new Date(),
        status: STATUS.PENDING,
      });
    } else if (data.status == STATUS.PENDING) {
      Object.assign(this.data, {
        refund_date: new Date(),
        status: STATUS.REFUNDED,
      });
    }

    return;
  }

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

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

  get entityTarget(): any {
    return RefundModel;
  }

  get eventTopics(): EventTopics[] {
    return [
      {
        topic: RefundChangeStatusEvent,
        relations: ['transaction'],
      },
    ];
  }
}
