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

type GetCustomerUseCaseInput = {
  companyId: UniqueID;
  customer_id: string;
};

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

  public execute(params: GetCustomerUseCaseInput) {
    const { customer_id, companyId } = params;

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

    const customerId = idOrError.data;
    const presenter = this.presenterRegistry.getPresenter({
      resource: "customer",
      projection: "FULL",
    }) as CustomerFullPresenter;

    return this.transactionManager.complete(async (transaction) => {
      try {
        const customerOrError = await this.service.getCustomerByIdInCompany(
          companyId,
          customerId,
          transaction
        );

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

        const customer = customerOrError.data;
        const dto = presenter.toOutput(customer);

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