import { IUseCase, IUseCaseError, UseCaseError } from "@/contexts/common/application/useCases";
import { IRepositoryManager } from "@/contexts/common/domain";
import { Collection, ICollection, IQueryCriteria, Result } from "@shared/contexts";

import { IInfrastructureError } from "@/contexts/common/infrastructure";
import { ISequelizeAdapter } from "@/contexts/common/infrastructure/sequelize";
import { Dealer } from "../../domain";
import { IDealerRepository } from "../../domain/repository";

export interface IListDealersParams {
  queryCriteria: IQueryCriteria;
}

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

export class ListDealersUseCase
  implements IUseCase<IListDealersParams, Promise<ListDealersResult>>
{
  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(params: Partial<IListDealersParams>): Promise<ListDealersResult> {
    const { queryCriteria } = params;

    return this.findDealers(queryCriteria);
  }

  private async findDealers(queryCriteria) {
    const transaction = this._adapter.startTransaction();
    const dealerRepoBuilder = this.getRepositoryByName<IDealerRepository>("Dealer");

    let dealers: ICollection<Dealer> = new Collection();

    try {
      await transaction.complete(async (t) => {
        dealers = await dealerRepoBuilder({ transaction: t }).findAll(queryCriteria);
      });
      return Result.ok(dealers);
    } catch (error: unknown) {
      const _error = error as IInfrastructureError;
      return Result.fail(
        UseCaseError.create(
          UseCaseError.REPOSITORY_ERROR,
          "Error al listar los distribuidores",
          _error
        )
      );
    }
  }
}
