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 { IQuoteRepository } from "../../domain";

export interface IDeleteQuoteUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
}

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

export class DeleteQuoteUseCase
  implements IUseCase<IDeleteQuoteUseCaseRequest, Promise<DeleteQuoteResponseOrError>>
{
  private _adapter: ISequelizeAdapter;
  private _repositoryManager: IRepositoryManager;

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

  async execute(request: IDeleteQuoteUseCaseRequest): Promise<DeleteQuoteResponseOrError> {
    const { id: QuoteId } = request;

    const transaction = this._adapter.startTransaction();
    const QuoteRepoBuilder = this._getQuoteRepository();

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

      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")
      );
    }
  }

  private _getQuoteRepository() {
    return this._repositoryManager.getRepository<IQuoteRepository>("Quote");
  }
}
