import { IUseCase, IUseCaseError, UseCaseError } from "@/contexts/common/application/useCases";
import { IRepositoryManager } from "@/contexts/common/domain";
import { Collection, ICollection, IQueryCriteria, Result } from "@shared/contexts";

import { IInfrastructureError } from "@/contexts/common/infrastructure";
import { ISequelizeAdapter } from "@/contexts/common/infrastructure/sequelize";
import { User } from "../domain";
import { IUserRepository } from "../domain/repository";

export interface IListUsersParams {
  queryCriteria: IQueryCriteria;
}

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

export class ListUsersUseCase implements IUseCase<IListUsersParams, Promise<ListUsersResult>> {
  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(params: Partial<IListUsersParams>): Promise<ListUsersResult> {
    const { queryCriteria } = params;

    return this.findUsers(queryCriteria);
  }

  private async findUsers(queryCriteria) {
    const transaction = this._adapter.startTransaction();
    const userRepoBuilder = this.getRepositoryByName<IUserRepository>("User");

    let users: ICollection<User> = new Collection();

    try {
      await transaction.complete(async (t) => {
        users = await userRepoBuilder({ transaction: t }).findAll(queryCriteria);
      });
      return Result.ok(users);
    } catch (error: unknown) {
      const _error = error as IInfrastructureError;
      return Result.fail(
        UseCaseError.create(UseCaseError.REPOSITORY_ERROR, "Error al listar los usuarios", _error)
      );
    }
  }
}
