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

import { IInfrastructureError } from "@/contexts/common/infrastructure";
import { Dealer } from "../../domain/entities/Dealer/Dealer";

export interface IGetDealerByUserByUserUseCaseRequest extends IUseCaseRequest {
  userId: UniqueID;
}

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

export class GetDealerByUserUseCase
  implements
    IUseCase<IGetDealerByUserByUserUseCaseRequest, Promise<GetDealerByUserResponseOrError>>
{
  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: IGetDealerByUserByUserUseCaseRequest
  ): Promise<GetDealerByUserResponseOrError> {
    const { userId } = request;

    // Validación de datos
    // No hay en este caso

    return await this.getUserDealer(userId);
  }

  private async getUserDealer(userId: UniqueID) {
    const transaction = this._adapter.startTransaction();
    const dealerRepoBuilder = this.getRepositoryByName<IDealerRepository>("Dealer");

    let dealer: Dealer | null = null;

    try {
      await transaction.complete(async (t) => {
        const dealerRepo = dealerRepoBuilder({ transaction: t });
        dealer = await dealerRepo.getByUserId(userId);
      });

      if (!dealer) {
        return Result.fail(UseCaseError.create(UseCaseError.NOT_FOUND_ERROR, "Dealer not found"));
      }

      return Result.ok<Dealer>(dealer!);
    } catch (error: unknown) {
      const _error = error as IInfrastructureError;
      return Result.fail(
        UseCaseError.create(
          UseCaseError.REPOSITORY_ERROR,
          "Error al consultar el distribuidor",
          _error
        )
      );
    }
  }
}
