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

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

export class GetCustomerInvoiceUseCase {
  constructor(
    private readonly service: CustomerInvoiceApplicationService,
    private readonly transactionManager: ITransactionManager,
    private readonly presenterRegistry: IPresenterRegistry
  ) {}

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

    const idOrError = UniqueID.create(invoice_id);
    if (idOrError.isFailure) {
      return Result.fail(idOrError.error);
    }

    const invoiceId = idOrError.data;
    const presenter = this.presenterRegistry.getPresenter({
      resource: "customer-invoice",
      projection: "FULL",
    }) as CustomerInvoiceFullPresenter;

    return this.transactionManager.complete(async (transaction) => {
      try {
        const invoiceOrError = await this.service.getInvoiceByIdInCompany(
          companyId,
          invoiceId,
          transaction
        );
        if (invoiceOrError.isFailure) {
          return Result.fail(invoiceOrError.error);
        }

        const customerInvoice = invoiceOrError.data;
        const dto = presenter.toOutput(customerInvoice);

        return Result.ok(dto);
      } catch (error: unknown) {
        return Result.fail(error as Error);
      }
    });
  }
}
