import {
  IUseCase,
  IUseCaseError,
  IUseCaseRequest,
  UseCaseError,
} from "@/contexts/common/application/useCases";
import { IRepositoryManager } from "@/contexts/common/domain";
import { ISequelizeAdapter } from "@/contexts/common/infrastructure/sequelize";
import { Result, UniqueID } from "@shared/contexts";
import { IDealerRepository } from "../../domain";

export interface IDeleteDealerUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
}

export type DeleteDealerResponseOrError =
  | Result<never, IUseCaseError> // Misc errors (value objects)
  | Result<void, never>; // Success!

export class DeleteDealerUseCase
  implements IUseCase<IDeleteDealerUseCaseRequest, Promise<DeleteDealerResponseOrError>>
{
  private _adapter: ISequelizeAdapter;
  private _repositoryManager: IRepositoryManager;

  constructor(props: { adapter: ISequelizeAdapter; repositoryManager: IRepositoryManager }) {
    this._adapter = props.adapter;
    this._repositoryManager = props.repositoryManager;
  }

  private getRepositoryByName<T>(name: string) {
    return this._repositoryManager.getRepository<T>(name);
  }

  async execute(request: IDeleteDealerUseCaseRequest): Promise<DeleteDealerResponseOrError> {
    const { id: dealerId } = request;

    const transaction = this._adapter.startTransaction();
    const dealerRepoBuilder = this.getRepositoryByName<IDealerRepository>("Dealer");

    try {
      await transaction.complete(async (t) => {
        const invoiceRepo = dealerRepoBuilder({ transaction: t });
        await invoiceRepo.removeById(dealerId);
      });

      return Result.ok<void>();
    } catch (error: unknown) {
      //const _error = error as IInfrastructureError;
      return Result.fail(
        UseCaseError.create(UseCaseError.REPOSITORY_ERROR, "Error al eliminar el usuario")
      );
    }
  }
}
