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

import { IInfrastructureError } from "@/contexts/common/infrastructure";

export interface IGetDealerUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
}

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

export class GetDealerUseCase
  implements IUseCase<IGetDealerUseCaseRequest, Promise<GetDealerResponseOrError>>
{
  private _adapter: ISequelizeAdapter;
  private _repositoryManager: IRepositoryManager;

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

  async execute(request: IGetDealerUseCaseRequest): Promise<GetDealerResponseOrError> {
    const { id } = request;

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

    return await this._findDealer(id);
  }

  private async _findDealer(id: UniqueID) {
    const transaction = this._adapter.startTransaction();
    const dealerRepository = this._getDealerRepository();

    let dealer: Dealer | null = null;

    try {
      await transaction.complete(async (t) => {
        const dealerRepo = dealerRepository({ transaction: t });
        dealer = await dealerRepo.getById(id);
      });

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

  private _getDealerRepository() {
    return this._repositoryManager.getRepository<IDealerRepository>("Dealer");
  }
}
