import { IPresenterRegistry, ITransactionManager } from "@erp/core/api";
import { Criteria } from "@repo/rdx-criteria/server";
import { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { Transaction } from "sequelize";
import { ListCustomersResponseDTO } from "../../../common/dto";
import { CustomerApplicationService } from "../../application";
import { ListCustomersPresenter } from "../presenters";

type ListCustomersUseCaseInput = {
  companyId: UniqueID;
  criteria: Criteria;
};

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

  public execute(
    params: ListCustomersUseCaseInput
  ): Promise<Result<ListCustomersResponseDTO, Error>> {
    const { criteria, companyId } = params;
    const presenter = this.presenterRegistry.getPresenter({
      resource: "customer",
      projection: "LIST",
    }) as ListCustomersPresenter;

    return this.transactionManager.complete(async (transaction: Transaction) => {
      try {
        const result = await this.service.findCustomerByCriteriaInCompany(
          companyId,
          criteria,
          transaction
        );

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

        const customers = result.data;
        const dto = presenter.toOutput({
          customers,
          criteria,
        });

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