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

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

export class DeleteCustomerUseCase {
  constructor(
    private readonly service: CustomerApplicationService,
    private readonly transactionManager: ITransactionManager
  ) {}

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

    const idOrError = UniqueID.create(customer_id);

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

    const customerId = idOrError.data;

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

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

        const customerExists = existsCheck.data;

        if (!customerExists) {
          return Result.fail(new EntityNotFoundError("Customer", "id", customerId.toString()));
        }

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