import { EntityNotFoundError, ITransactionManager } from "@erp/core/api";
import { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { CustomerInvoiceApplicationService } from "../../application";

type DeleteCustomerInvoiceUseCaseInput = {
  companyId: UniqueID;
  invoice_id: string;
};

export class DeleteCustomerInvoiceUseCase {
  constructor(
    private readonly service: CustomerInvoiceApplicationService,
    private readonly transactionManager: ITransactionManager
  ) {}

  public execute(params: DeleteCustomerInvoiceUseCaseInput) {
    const { invoice_id, companyId } = params;

    const idOrError = UniqueID.create(invoice_id);

    if (idOrError.isFailure) {
      return Result.fail(idOrError.error);
    }

    const invoiceId = idOrError.data;

    return this.transactionManager.complete(async (transaction) => {
      try {
        const existsCheck = await this.service.existsByIdInCompany(
          companyId,
          invoiceId,
          transaction
        );

        if (existsCheck.isFailure) {
          return Result.fail(existsCheck.error);
        }

        const invoiceExists = existsCheck.data;

        if (!invoiceExists) {
          return Result.fail(
            new EntityNotFoundError("Customer invoice", "id", invoiceId.toString())
          );
        }

        return await this.service.deleteInvoiceByIdInCompany(companyId, invoiceId, transaction);
      } catch (error: unknown) {
        return Result.fail(error as Error);
      }
    });
  }
}
