import { ListAccountsUseCase } from "@/contexts/accounts/application";
import { ExpressController } from "@/core/common/presentation";
import { IListAccountsPresenter } from "./list-accounts.presenter";

export class ListAccountsController extends ExpressController {
  public constructor(
    private readonly listAccounts: ListAccountsUseCase,
    private readonly presenter: IListAccountsPresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const accountsOrError = await this.listAccounts.execute();

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

    return this.ok(this.presenter.toDTO(accountsOrError.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);
  }
}
