import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-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 { 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';

@Injectable()
export class BatchConfirmRefundManager extends BaseBatchUpdateStatusManager<RefundEntity> {
  async validateData(data: RefundEntity): Promise<void> {
    if (
      this.data.status == STATUS.DRAFT &&
      data['trnsaction']?.status != STATUS.SETTLED &&
      this.data.status == STATUS.PENDING &&
      data['trnsaction']?.status != STATUS.PROCESS_REFUND
    ) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! hanya data dengan status ${STATUS.SETTLED} dapat dikembalikan`,
        error: 'Unprocessable Entity',
      });
    } else if (![STATUS.DRAFT, STATUS.PENDING].includes(data.status)) {
      throw new UnprocessableEntityException({
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message: `Gagal! hanya data dengan status ${STATUS.DRAFT} and ${STATUS.PENDING} dapat di${this.dataStatus}`,
        error: 'Unprocessable Entity',
      });
    }

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

  beforeProcess(): Promise<void> {
    this.relations = ['transaction'];
    return;
  }

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

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

  get entityTarget(): any {
    return RefundModel;
  }

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

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