import { ListInvoicesUseCase } from "@/contexts/invoices/application";
import { ExpressController } from "@/core";
import { IListInvoicesPresenter } from "./presenter";

export class ListInvoicesController extends ExpressController {
  public constructor(
    private readonly listInvoices: ListInvoicesUseCase,
    private readonly presenter: IListInvoicesPresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const { query } = this.req;
    //const queryCriteria: IQueryCriteria = QueryCriteriaService.parse(query);

    const invoicesOrError = await this.listInvoices.execute(/* queryCriteria */);

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

    return this.ok(
      this.presenter.toDTO(
        invoicesOrError.data /*, {
      page: queryCriteria.pagination.offset,
      limit: queryCriteria.pagination.limit,
    }*/
      )
    );
  }

  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);
  }
}
