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

export interface IDeleteUserUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
}

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

export class DeleteUserUseCase
  implements
    IUseCase<IDeleteUserUseCaseRequest, Promise<DeleteUserResponseOrError>>
{
  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: IDeleteUserUseCaseRequest,
  ): Promise<DeleteUserResponseOrError> {
    const { id: userId } = request;

    const transaction = this._adapter.startTransaction();
    const userRepoBuilder = this.getRepositoryByName<IUserRepository>("User");

    try {
      await transaction.complete(async (t) => {
        const invoiceRepo = userRepoBuilder({ transaction: t });
        await invoiceRepo.removeById(userId);
      });

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