import { ListUsersUseCase } from "@/contexts/auth/application";
import { ExpressController } from "@/core/common/presentation";
import { IListUsersPresenter } from "./list-users.presenter";

export class ListUsersController extends ExpressController {
  public constructor(
    private readonly listUsers: ListUsersUseCase,
    private readonly presenter: IListUsersPresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const usersOrError = await this.listUsers.execute();

    if (usersOrError.isFailure) {
      return this.handleError(usersOrError.error);
    }

    return this.ok(this.presenter.toDTO(usersOrError.data));
  }

  private handleError(error: Error) {
    const message = error.message;

    if (
      message.includes("Database connection lost") ||
      message.includes("Database request timed out")
    ) {
      return this.unavailableError(
        "Database service is currently unavailable. Please try again later."
      );
    }

    return this.conflictError(message);
  }
}
