import { ListCustomerInvoicesUseCase } from "@/contexts/customer-billing/application";
import { ExpressController } from "@/core/common/presentation";
import { IListCustomerInvoicesPresenter } from "./list-customer-invoices.presenter";

export class ListCustomerInvoicesController extends ExpressController {
  public constructor(
    private readonly listCustomerInvoices: ListCustomerInvoicesUseCase,
    private readonly presenter: IListCustomerInvoicesPresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const customersOrError = await this.listCustomerInvoices.execute();

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

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