import { IPresenterRegistry, ITransactionManager } from "@erp/core/api";
import { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { Transaction } from "sequelize";
import { UpdateCustomerByIdRequestDTO } from "../../../../common/dto";
import { CustomerPatchProps } from "../../../domain";
import { CustomerApplicationService } from "../../customer-application.service";
import { CustomerFullPresenter } from "../../presenters";
import { mapDTOToUpdateCustomerPatchProps } from "./map-dto-to-update-customer-props";

type UpdateCustomerUseCaseInput = {
  companyId: UniqueID;
  customer_id: string;
  dto: UpdateCustomerByIdRequestDTO;
};

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

  public execute(params: UpdateCustomerUseCaseInput) {
    const { companyId, customer_id, dto } = 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;

    // Mapear DTO → props de dominio
    const patchPropsResult = mapDTOToUpdateCustomerPatchProps(dto);
    if (patchPropsResult.isFailure) {
      return Result.fail(patchPropsResult.error);
    }

    const patchProps: CustomerPatchProps = patchPropsResult.data;

    return this.transactionManager.complete(async (transaction: Transaction) => {
      try {
        const updatedCustomer = await this.service.patchCustomerByIdInCompany(
          companyId,
          customerId,
          patchProps,
          transaction
        );

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

        const customerOrError = await this.service.updateCustomerInCompany(
          companyId,
          updatedCustomer.data,
          transaction
        );
        const customer = customerOrError.data;
        const dto = presenter.toOutput(customer);
        return Result.ok(dto);
      } catch (error: unknown) {
        return Result.fail(error as Error);
      }
    });
  }
}
