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 IGetProfileLogoUseCaseRequest extends IUseCaseRequest {
  userId: UniqueID;
}

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

export class GetProfileLogoUseCase
  implements IUseCase<IGetProfileLogoUseCaseRequest, Promise<GetProfileLogoResponseOrError>>
{
  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: IGetProfileLogoUseCaseRequest): Promise<GetProfileLogoResponseOrError> {
    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.getByUserId(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;
      console.error(error);
      return Result.fail(
        UseCaseError.create(UseCaseError.REPOSITORY_ERROR, "Error al consultar el usuario", _error)
      );
    }
  }
}
