import { GetInvoiceUseCase } from "@contexts/invoices/application";
import { UniqueID } from "core/common/domain";
import { ExpressController } from "core/common/presentation";
import { IGetInvoicePresenter } from "./presenter";

export class GetInvoiceController extends ExpressController {
  public constructor(
    private readonly getInvoice: GetInvoiceUseCase,
    private readonly presenter: IGetInvoicePresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const { invoiceId } = this.req.params;

    // Validar ID
    const invoiceIdOrError = UniqueID.create(invoiceId);
    if (invoiceIdOrError.isFailure) return this.invalidInputError("Invoice ID not valid");

    const invoiceOrError = await this.getInvoice.execute(invoiceIdOrError.data);

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

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