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 { IInfrastructureError } from "@/contexts/common/infrastructure";
import { IProfileRepository, Profile } from "../domain";

export interface IGetProfileUseCaseRequest extends IUseCaseRequest {
  userId: UniqueID;
}

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

export class GetProfileByUserIdUseCase
  implements IUseCase<IGetProfileUseCaseRequest, Promise<GetProfileResponseOrError>>
{
  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: IGetProfileUseCaseRequest): Promise<GetProfileResponseOrError> {
    const { userId } = request;

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

    return await this._getProfileDealer(userId);
  }

  private async _getProfileDealer(userId: UniqueID) {
    const transaction = this._adapter.startTransaction();
    const dealerRepoBuilder = this.getRepositoryByName<IProfileRepository>("Profile");

    let profile: Profile | null = null;

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

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

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

  private _getProfileRepository() {
    return this._repositoryManager.getRepository<IProfileRepository>("Profile");
  }
}
