import { ExpressController } from "@/core/common/presentation";
import { ListContactsUseCase } from "../../../application";
import { IListContactsPresenter } from "./list-contacts.presenter";

export class ListContactsController extends ExpressController {
  public constructor(
    private readonly listContacts: ListContactsUseCase,
    private readonly presenter: IListContactsPresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const contactsOrError = await this.listContacts.execute();

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

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